From f30f88c4d33399a0e05b54c2192994f4b7cb9fa7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:54:07 +0100 Subject: [PATCH 01/20] Give the HTTPS browser test program the light-header unit it registers (#766) --- test/web/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 477bb6a4..522dfa9e 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -312,7 +312,7 @@ if(_browser_tests_available) file(STRINGS "${_tls_fixture}/spki.txt" _tls_spki LIMIT_COUNT 1) webfront_add_test_program(webtest_tls JasmineTest.cpp WITH_WEBTEST DEFINITIONS WEBFRONT_TEST_TLS_FIXTURE="${_tls_fixture}" WEBFRONT_TEST_MEDIA_FILE="${CMAKE_CURRENT_SOURCE_DIR}/fixtures/media/seek.webm") - target_sources(webtest_tls PRIVATE RestartableServer.cpp) + target_sources(webtest_tls PRIVATE RestartableServer.cpp ../unit/BridgeLightPage.cpp) target_link_libraries(webtest_tls PRIVATE WebFront_boing) endif() else() From c78e7633aa9e1817dc9b2cebb1432d90c57a975a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:54:07 +0100 Subject: [PATCH 02/20] Measure image streams end to end with a manual benchmark (#769) --- cmake/ImageStreamBenchmark.cmake | 35 ++ cmake/ImageStreamJpeg.cmake | 25 + test/web/CMakeLists.txt | 6 + test/web/ImageStreamBenchmark.cpp | 621 +++++++++++++++++++++++++ test/web/ImageStreamWebExtension.cpp | 67 +++ test/web/JasmineTest.cpp | 7 - test/web/image-stream/bench.html | 10 + test/web/image-stream/bench.js | 175 +++++++ test/web/image-stream/host-encoders.sh | 43 ++ test/web/suite/bench/image-streams.mjs | 61 --- 10 files changed, 982 insertions(+), 68 deletions(-) create mode 100644 cmake/ImageStreamBenchmark.cmake create mode 100644 cmake/ImageStreamJpeg.cmake create mode 100644 test/web/ImageStreamBenchmark.cpp create mode 100644 test/web/ImageStreamWebExtension.cpp create mode 100644 test/web/image-stream/bench.html create mode 100644 test/web/image-stream/bench.js create mode 100644 test/web/image-stream/host-encoders.sh delete mode 100644 test/web/suite/bench/image-streams.mjs diff --git a/cmake/ImageStreamBenchmark.cmake b/cmake/ImageStreamBenchmark.cmake new file mode 100644 index 00000000..cc6e33a3 --- /dev/null +++ b/cmake/ImageStreamBenchmark.cmake @@ -0,0 +1,35 @@ +# Manual measurement of image streams (#769, docs/IMAGE_STREAMS.md): never built by default, never a CTest case. +# cmake --build --target image_stream_report +# builds image_stream_bench for the browser test frontend, runs it and writes /image-streams.json. A display is +# needed (run it under xvfb-run without one). +function(webfront_add_image_stream_benchmark source) + webfront_add_test_program(image_stream_bench ImageStreamBenchmark.cpp EXCLUDE_FROM_ALL) + include(ImageStreamJpeg) + webfront_link_image_stream_jpeg(image_stream_bench WEBFRONT_BENCH_JPEG) + if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "WebKitGTK") + find_package(PkgConfig QUIET) + if(PKG_CONFIG_FOUND) + pkg_check_modules(WEBFRONT_WEB_EXTENSION QUIET IMPORTED_TARGET webkitgtk-web-process-extension-6.0) + endif() + if(WEBFRONT_WEB_EXTENSION_FOUND) + set(directory "${CMAKE_CURRENT_BINARY_DIR}/image-stream-extension") + add_library(image_stream_extension MODULE EXCLUDE_FROM_ALL "${source}/ImageStreamWebExtension.cpp") + target_link_libraries(image_stream_extension PRIVATE PkgConfig::WEBFRONT_WEB_EXTENSION ${CMAKE_DL_LIBS} rt) + set_target_properties(image_stream_extension PROPERTIES LIBRARY_OUTPUT_DIRECTORY "${directory}") + add_dependencies(image_stream_bench image_stream_extension) + target_compile_definitions(image_stream_bench PRIVATE WEBFRONT_BENCH_SHM + "WEBFRONT_BENCH_EXTENSION_DIRECTORY=\"${directory}\"") + target_link_libraries(image_stream_bench PRIVATE rt) + else() + message(STATUS "image_stream_bench: no WebKitGTK web process extension headers, no shared memory track") + endif() + endif() + if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "WKWebView") + set_target_properties(image_stream_bench PROPERTIES MACOSX_BUNDLE TRUE + MACOSX_BUNDLE_GUI_IDENTIFIER "org.webfront.tests.image-stream-bench" + MACOSX_BUNDLE_INFO_PLIST "${PROJECT_SOURCE_DIR}/test/cmake/WKWebViewTestInfo.plist.in") + endif() + add_custom_target(image_stream_report + COMMAND image_stream_bench "${source}/image-stream" "${CMAKE_BINARY_DIR}/image-streams.json" + USES_TERMINAL VERBATIM) +endfunction() diff --git a/cmake/ImageStreamJpeg.cmake b/cmake/ImageStreamJpeg.cmake new file mode 100644 index 00000000..4db4c48f --- /dev/null +++ b/cmake/ImageStreamJpeg.cmake @@ -0,0 +1,25 @@ +# The optional JPEG library of the image stream example and of its measurement and test (docs/IMAGE_STREAMS.md). Searched +# by default on Linux only: elsewhere a runner or a developer machine often holds a libjpeg of another toolchain (Strawberry +# Perl, Mono) that find_package would pick. Without it the host sends pixels, and the benchmark lets the page encode. +include_guard(GLOBAL) + +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + set(_webfront_image_jpeg_default ON) +else() + set(_webfront_image_jpeg_default OFF) +endif() +option(WEBFRONT_IMAGE_STREAM_JPEG "Encode the images of the image stream example with libjpeg" ${_webfront_image_jpeg_default}) + +# webfront_link_image_stream_jpeg( ): links libjpeg and defines when it is found. +function(webfront_link_image_stream_jpeg target definition) + if(NOT WEBFRONT_IMAGE_STREAM_JPEG) + return() + endif() + find_package(JPEG QUIET) + if(JPEG_FOUND) + target_link_libraries(${target} PRIVATE JPEG::JPEG) + target_compile_definitions(${target} PRIVATE ${definition}) + else() + message(STATUS "${target}: no JPEG library found, built without JPEG encoding") + endif() +endfunction() diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 522dfa9e..76ef384c 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -65,6 +65,12 @@ if(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_OPTION} set_tests_properties(FrontendLifecycleWatchdog PROPERTIES TIMEOUT 10 LABELS fast) endif() +# Manual measurement of image streams (#769): never built by default nor run by CTest. +if(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_OPTION}) + include(ImageStreamBenchmark) + webfront_add_image_stream_benchmark("${CMAKE_CURRENT_SOURCE_DIR}") +endif() + # Several applications with no configured port: all start, answer on the port they announce and stop (#617). The first one # takes 9002 when it is free, hence the lock. add_executable(multi_instance MultiInstance.cpp) diff --git a/test/web/ImageStreamBenchmark.cpp b/test/web/ImageStreamBenchmark.cpp new file mode 100644 index 00000000..b7e7cefe --- /dev/null +++ b/test/web/ImageStreamBenchmark.cpp @@ -0,0 +1,621 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/web +// Role: End-to-end measurement of the ways to send images from the host to the page (#769). +// Thread: multi-thread | Alloc: unrestricted +// LLM: manual benchmark; fails on a wrong run, never on a timing + +// The host produces RGBA frames, sends them by one of several tracks, and the page draws each one and acknowledges it: +// latency is the time from the start of a frame's preparation to the reception of its acknowledgement, read on the host's +// clock only. At most `window` frames are unacknowledged; a tick of the source that finds the window full is a skipped +// frame. See docs/IMAGE_STREAMS.md. +// image_stream_bench [] [--seconds N] +// image_stream_bench --dump-frames (the frames, for image-stream/host-encoders.sh) + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WEBFRONT_BENCH_JPEG +// clang-format off +#include +#include +// clang-format on +#endif + +#ifdef _WIN32 + #include + #include +#else + #include + #include +#endif + +#ifdef WEBFRONT_BENCH_SHM + #include + #include + #include +#endif + +#ifndef WEBFRONT_TEST_FRONTEND + #error "WEBFRONT_TEST_FRONTEND names the browser test frontend" +#endif + +namespace { + +using Clock = std::chrono::steady_clock; + +constexpr int poolSize = 16; +constexpr unsigned sharedSlots = 3; // more than the window, so the slot being read is never rewritten + +/// Gradients, a moving checkerboard and a few bits of noise in every channel: neither the best nor the worst case of a codec. +std::vector makeFrame(int width, int height, int index) { + std::vector pixels(static_cast(width) * static_cast(height) * 4); + std::uint32_t seed = 1u + static_cast(index) * 2654435761u; + std::size_t at = 0; + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x, at += 4) { + seed ^= seed << 13; + seed ^= seed >> 17; + seed ^= seed << 5; + const int check = (((x + index * 4) >> 5) + (y >> 5)) & 1; + pixels[at] = static_cast(static_cast(x * 248 / width) + (seed & 7u)); + pixels[at + 1] = static_cast((check ? 220u : 30u) + ((seed >> 3) & 7u)); + pixels[at + 2] = static_cast(static_cast(y * 248 / height) + ((seed >> 6) & 7u)); + pixels[at + 3] = 255; + } + return pixels; +} + +#ifdef WEBFRONT_BENCH_JPEG +constexpr bool hostEncodes = true; + +std::vector encodeJpeg(const std::vector& rgba, int width, int height) { + jpeg_compress_struct info{}; + jpeg_error_mgr errors{}; + info.err = jpeg_std_error(&errors); // the default handler ends the process: acceptable for a benchmark + jpeg_create_compress(&info); + unsigned char* output = nullptr; + unsigned long size = 0; + jpeg_mem_dest(&info, &output, &size); + info.image_width = static_cast(width); + info.image_height = static_cast(height); + #ifdef JCS_EXTENSIONS + info.input_components = 4; + info.in_color_space = JCS_EXT_RGBA; + #else + info.input_components = 3; + info.in_color_space = JCS_RGB; + std::vector row(static_cast(width) * 3); + #endif + jpeg_set_defaults(&info); + jpeg_set_quality(&info, 85, TRUE); + jpeg_start_compress(&info, TRUE); + while (info.next_scanline < info.image_height) { + const auto* source = rgba.data() + static_cast(info.next_scanline) * static_cast(width) * 4; + #ifdef JCS_EXTENSIONS + auto* line = const_cast(source); + #else + for (int x = 0; x < width; ++x) + std::memcpy(row.data() + 3 * x, source + 4 * x, 3); + auto* line = row.data(); + #endif + jpeg_write_scanlines(&info, &line, 1); + } + jpeg_finish_compress(&info); + std::vector result(output, output + size); + jpeg_destroy_compress(&info); + std::free(output); + return result; +} +#else +constexpr bool hostEncodes = false; +std::vector encodeJpeg(const std::vector&, int, int) { + return {}; +} +#endif + +/// CPU seconds consumed so far by this process (host) and by its descendants (the engine's own processes), when known. +struct CpuTimes { + double host = 0; + std::optional engine; +}; + +#ifdef _WIN32 +double processSeconds(HANDLE process) { + FILETIME created, exited, kernel, user; + if (!GetProcessTimes(process, &created, &exited, &kernel, &user)) + return 0; + const auto seconds = [](const FILETIME& time) { + return static_cast((static_cast(time.dwHighDateTime) << 32) | time.dwLowDateTime) * 1e-7; + }; + return seconds(kernel) + seconds(user); +} + +CpuTimes cpuTimes() { + CpuTimes times{.host = processSeconds(GetCurrentProcess()), .engine = std::nullopt}; + const HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); + if (snapshot == INVALID_HANDLE_VALUE) + return times; + std::multimap children; + PROCESSENTRY32 entry{}; + entry.dwSize = sizeof(entry); + for (BOOL more = Process32First(snapshot, &entry); more; more = Process32Next(snapshot, &entry)) + children.emplace(entry.th32ParentProcessID, entry.th32ProcessID); + CloseHandle(snapshot); + std::vector pending{GetCurrentProcessId()}; + for (std::size_t i = 0; i < pending.size() && pending.size() < 1000; ++i) { + const auto [first, last] = children.equal_range(pending[i]); + for (auto child = first; child != last; ++child) { + if (std::ranges::find(pending, child->second) != pending.end()) + continue; + pending.push_back(child->second); + if (const HANDLE process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, child->second)) { + times.engine = times.engine.value_or(0) + processSeconds(process); + CloseHandle(process); + } + } + } + return times; +} +#else +CpuTimes cpuTimes() { + rusage usage{}; + getrusage(RUSAGE_SELF, &usage); + const auto seconds = [](const timeval& time) { + return static_cast(time.tv_sec) + static_cast(time.tv_usec) * 1e-6; + }; + CpuTimes times{.host = seconds(usage.ru_utime) + seconds(usage.ru_stime), .engine = std::nullopt}; + #ifdef __linux__ + // pid -> (parent, utime + stime in ticks) + std::map> processes; + std::error_code error; + for (const auto& item : std::filesystem::directory_iterator("/proc", error)) { + const auto name = item.path().filename().string(); + if (name.find_first_not_of("0123456789") != std::string::npos) + continue; + std::ifstream stat(item.path() / "stat"); + std::string line; + std::getline(stat, line); + const auto afterName = line.rfind(')'); + if (afterName == std::string::npos) + continue; + std::istringstream fields(line.substr(afterName + 1)); + std::string state, skipped; + long parent = 0; + double user = 0, system = 0; + fields >> state >> parent; + for (int i = 0; i < 9; ++i) + fields >> skipped; + fields >> user >> system; + processes[std::stol(name)] = {parent, user + system}; + } + const auto ticks = static_cast(sysconf(_SC_CLK_TCK)); + const long self = getpid(); + for (const auto& [pid, process] : processes) { + long parent = process.first; + for (int depth = 0; depth < 16 && parent > 1; ++depth) { + if (parent == self) { + times.engine = times.engine.value_or(0) + process.second / ticks; + break; + } + const auto up = processes.find(parent); + parent = up == processes.end() ? 0 : up->second.first; + } + } + #endif // on macOS the web content processes are launched by the system, not by this process: not measured + return times; +} +#endif + +#ifdef WEBFRONT_BENCH_SHM +/// A POSIX shared memory object the web process extension maps (test/web/ImageStreamWebExtension.cpp). +struct SharedFrames { + static constexpr std::size_t slotSize = 1920 * 1080 * 4; + std::string name = "/webfront-image-bench-" + std::to_string(getpid()); + std::uint8_t* data = nullptr; + + SharedFrames() { + const int fd = shm_open(name.c_str(), O_CREAT | O_EXCL | O_RDWR, 0600); + if (fd < 0 || ftruncate(fd, static_cast(slotSize * sharedSlots)) != 0) + throw std::runtime_error("cannot create the shared memory object"); + auto* mapped = mmap(nullptr, slotSize * sharedSlots, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + close(fd); + if (mapped == MAP_FAILED) + throw std::runtime_error("cannot map the shared memory object"); + data = static_cast(mapped); + } + SharedFrames(const SharedFrames&) = delete; + SharedFrames& operator=(const SharedFrames&) = delete; + ~SharedFrames() { + munmap(data, slotSize * sharedSlots); + shm_unlink(name.c_str()); + } +}; +SharedFrames* sharedFrames = nullptr; +#endif + +/// One measured case: a track, a size and a source rate. Shared between the producer, the route and the callbacks. +struct Run { + std::string track; + int width = 0, height = 0, fps = 0, window = 2; + + std::mutex mutex; + std::condition_variable changed; + bool stopping = false; + std::vector> pool, encoded; // raw frames; their JPEG when the page supplied it + std::map inFlight; + std::deque>> mailbox; // the route's next frames, each with its header + std::uint32_t sequence = 0; + // Counted after the warm-up. + bool measuring = false; + std::uint64_t delivered = 0, skipped = 0, bytes = 0, prepared = 0; + double encodeMs = 0, pageMs = 0; + std::vector latencies; +}; + +std::string number(std::optional value) { + if (!value) + return "null"; + char buffer[32]; + std::snprintf(buffer, sizeof(buffer), "%.2f", *value); + return buffer; +} + +#ifdef WEBFRONT_BENCH_SHM +namespace gtk = webfront::frontend::detail::webkitgtk; + +// The WebKitGTK window of the adapter, with the web process extension that exposes the shared memory to the page: the +// extension directory is given to the view's context before the first navigation. +struct BenchmarkFrontend : webfront::frontend::EmbeddedFrontend { + static constexpr bool requiresMainThread = true; + static constexpr bool secondaryWindows = false; + static constexpr bool compiled = true; + static constexpr std::string_view name = "WebKitGTKFrontend"; + static constexpr std::string_view enable = ""; + using Options = webfront::frontend::ViewOptions; + using Host = webfront::frontend::WebKitGTKHost; + + static void initializeNative() { + gtk::initialize(); + } + static void openNative(std::string_view address, std::string_view port, std::string_view page, const Options& options) { + auto open = gtk::openOptionsOf(options); + open.configure = [](gtk::Session& session) { + void* module = dlopen("libwebkitgtk-6.0.so.4", RTLD_NOW | RTLD_LOCAL | RTLD_NOLOAD); + auto* getContext = module ? reinterpret_cast(dlsym(module, "webkit_web_view_get_context")) : nullptr; + auto* setDirectory = module + ? reinterpret_cast(dlsym(module, "webkit_web_context_set_web_process_extensions_directory")) + : nullptr; + if (!getContext || !setDirectory) + throw std::runtime_error("WebKitGTK: no web process extension entry points"); + setDirectory(getContext(session.view), WEBFRONT_BENCH_EXTENSION_DIRECTORY); + }; + gtk::open(address, port, page, open, gtk::SandboxMode::development); + } + static void closeNative(const webfront::frontend::NativeWindowHandle& window) { + webfront::frontend::WebKitGTKFrontend::closeNative(window); + } +}; +using BenchFrontend = BenchmarkFrontend; +#else +using BenchFrontend = WEBFRONT_TEST_FRONTEND; +#endif + +using App = webfront::BasicWFWithFrontend, BenchFrontend>; + +class Bench { + App& app; + int seconds; + std::mutex runMutex; + std::shared_ptr run; + std::thread producer; + std::filesystem::path reportPath; + + std::shared_ptr current() { + std::scoped_lock lock(runMutex); + return run; + } + + static void produce(std::shared_ptr state, App::UI ui) { + const auto period = std::chrono::nanoseconds(state->fps > 0 ? 1'000'000'000 / state->fps : 0); + auto tick = Clock::now(); + const bool jpeg = state->track.starts_with("jpeg"); + const bool route = state->track.ends_with("route"); + for (;;) { + { + std::unique_lock lock(state->mutex); + const auto free = [&] { + return state->stopping || static_cast(state->inFlight.size()) < state->window; + }; + if (state->fps > 0) { + tick += period; + state->changed.wait_until(lock, tick, [&] { + return state->stopping; + }); + if (!state->stopping && !free()) { + if (state->measuring) + ++state->skipped; + continue; + } + } else + state->changed.wait(lock, free); + if (state->stopping) + return; + } + const auto start = Clock::now(); + const std::uint32_t sequence = ++state->sequence; + const auto& raw = state->pool[sequence % state->pool.size()]; + std::vector compressed; + double encodeMs = 0; + if (jpeg && hostEncodes) { + compressed = encodeJpeg(raw, state->width, state->height); + encodeMs = std::chrono::duration(Clock::now() - start).count(); + } else if (jpeg) + compressed = state->encoded[sequence % state->encoded.size()]; + const auto& payload = jpeg ? compressed : raw; + { + std::scoped_lock lock(state->mutex); + state->inFlight.emplace(sequence, start); + if (state->measuring) { + ++state->prepared; + state->bytes += payload.size(); + state->encodeMs += encodeMs; + } + } + try { + if (route) { + auto frame = std::make_shared>(8 + payload.size()); + const auto length = static_cast(payload.size()); + for (int i = 0; i < 4; ++i) { // little endian, as the page reads it + (*frame)[static_cast(i)] = static_cast(length >> (8 * i)); + (*frame)[static_cast(i + 4)] = static_cast(sequence >> (8 * i)); + } + std::memcpy(frame->data() + 8, payload.data(), payload.size()); + std::scoped_lock lock(state->mutex); + state->mailbox.push_back(std::move(frame)); // at most `window` of them + state->changed.notify_all(); + } +#ifdef WEBFRONT_BENCH_SHM + else if (state->track == "raw-shared") { + const auto slot = sequence % sharedSlots; + std::memcpy(sharedFrames->data + slot * SharedFrames::slotSize, payload.data(), payload.size()); + ui.jsFunction("bench.shared")(sequence, slot, static_cast(payload.size())); + } +#endif + else + ui.jsFunction("bench.frame")(sequence, payload); + } catch (const std::exception& error) { + std::cerr << "image stream bench: " << error.what() << '\n'; + return; + } + } + } + + void stopProducer() { + if (const auto state = current()) { + std::scoped_lock lock(state->mutex); + state->stopping = true; + state->changed.notify_all(); + } + if (producer.joinable()) + producer.join(); + } + + /// The streamed route: the response ends with the case. The body callback runs on a route worker, which it holds. + webfront::http::RouteReply frames() { + webfront::http::RouteReply reply; + reply.headers.emplace_back("Content-Type", "application/octet-stream"); + reply.headers.emplace_back("Cache-Control", "no-store"); + reply.body = [state = current(), frame = std::shared_ptr>{}, offset = std::size_t{0}]( + std::span chunk) mutable -> std::size_t { + if (!state) + return 0; + if (!frame || offset == frame->size()) { + std::unique_lock lock(state->mutex); + state->changed.wait_for(lock, std::chrono::seconds(5), [&] { + return state->stopping || !state->mailbox.empty(); + }); + if (state->stopping || state->mailbox.empty()) + return 0; + frame = std::move(state->mailbox.front()); + state->mailbox.pop_front(); + offset = 0; + } + const auto count = (std::min)(chunk.size(), frame->size() - offset); + std::memcpy(chunk.data(), frame->data() + offset, count); + offset += count; + return count; + }; + return reply; + } + +public: + webfront::http::RouteTable::Registration route; + bool reported = false; + + Bench(App& application, int duration, std::filesystem::path path) : app(application), seconds(duration), reportPath(std::move(path)) { + route = app.addRoute("/frames/", [this](const webfront::http::RouteRequest&) { + return frames(); + }); + app.cppFunction("benchProgress", [](const std::string& text) { + std::cout << "image stream bench: " << text << std::endl; + }); + app.cppFunction("benchConfig", [this] { + std::string tracks = "raw-bridge,raw-route,jpeg-bridge,jpeg-route"; +#ifdef WEBFRONT_BENCH_SHM + tracks += ",raw-shared"; +#endif + return std::string("{\"seconds\":") + std::to_string(seconds) + ",\"hostEncodes\":" + (hostEncodes ? "true" : "false") + + ",\"cores\":" + std::to_string(std::thread::hardware_concurrency()) + ",\"tracks\":\"" + tracks + "\"}"; + }); + app.cppFunction("benchPrepare", [this](std::string track, int width, int height, int fps) { + stopProducer(); + auto state = std::make_shared(); + state->track = std::move(track); + state->width = width; + state->height = height; + state->fps = fps; + for (int i = 0; i < poolSize; ++i) + state->pool.push_back(makeFrame(width, height, i)); + std::scoped_lock lock(runMutex); + run = std::move(state); + }); + // Without a JPEG library in the host, the page encodes the pool once: its JPEG tracks then have no encoding cost. + app.cppFunction("benchFrame", [this](int index) { + return current()->pool.at(static_cast(index)); + }); + app.cppFunction("benchEncoded", [this](const std::vector& jpeg) { + current()->encoded.push_back(jpeg); + }); + app.cppFunction("benchStart", [this](App::UI ui) { + producer = std::thread(produce, current(), ui); + }); + app.cppFunction("benchDrawn", [this](std::uint32_t sequence, double pageMs) { + const auto state = current(); + std::scoped_lock lock(state->mutex); + const auto sent = state->inFlight.find(sequence); + if (sent == state->inFlight.end()) + return; + if (state->measuring) { + ++state->delivered; + state->pageMs += pageMs; + state->latencies.push_back(std::chrono::duration(Clock::now() - sent->second).count()); + } + state->inFlight.erase(sent); + state->changed.notify_all(); + }); + // Runs the measured window after one second of warm-up and returns its figures as JSON. + app.cppFunction("benchMeasure", [this]() -> webfront::ResultTask { + const auto state = current(); + co_await app.resumeAfter(std::chrono::seconds(1)); + const auto before = cpuTimes(); + const auto start = Clock::now(); + { + std::scoped_lock lock(state->mutex); + state->measuring = true; + } + co_await app.resumeAfter(std::chrono::seconds(seconds)); + const auto after = cpuTimes(); + const auto wall = std::chrono::duration(Clock::now() - start).count(); + std::string json; + { + std::scoped_lock lock(state->mutex); + state->measuring = false; + auto& all = state->latencies; + std::ranges::sort(all); + const auto percentile = [&](double p) -> std::optional { + if (all.empty()) + return std::nullopt; + return all[static_cast(p * static_cast(all.size() - 1))]; + }; + const auto mean = [](double total, std::uint64_t count) -> std::optional { + return count ? std::optional(total / static_cast(count)) : std::nullopt; + }; + json = "{\"fps\":" + number(static_cast(state->delivered) / wall) + + ",\"skippedPerSecond\":" + number(static_cast(state->skipped) / wall) + ",\"latencyMs50\":" + number(percentile(0.5)) + + ",\"latencyMs95\":" + number(percentile(0.95)) + ",\"frameBytes\":" + number(mean(static_cast(state->bytes), state->prepared)) + + ",\"encodeMs\":" + number(hostEncodes && state->track.starts_with("jpeg") ? mean(state->encodeMs, state->prepared) : std::nullopt) + + ",\"pageMs\":" + number(mean(state->pageMs, state->delivered)) + ",\"hostCpu\":" + number((after.host - before.host) / wall) + + ",\"engineCpu\":" + number(after.engine && before.engine ? std::optional((*after.engine - *before.engine) / wall) : std::nullopt) + + "}"; + } + stopProducer(); + co_return json; + }); + app.cppFunction("benchReport", [this](const std::string& json) { + reported = true; + std::cout << "IMAGE-STREAMS " << json << std::endl; + if (!reportPath.empty()) + std::ofstream(reportPath, std::ios::binary) << json << '\n'; + app.requestClose(); + }); + } + + Bench(const Bench&) = delete; + Bench& operator=(const Bench&) = delete; + ~Bench() { + stopProducer(); + } +}; + +void dumpFrames(const std::filesystem::path& directory) { + std::filesystem::create_directories(directory); + for (const auto& [width, height] : { + std::pair{ 960, 720}, + std::pair{1920, 1080} + }) { + std::ofstream output(directory / (std::to_string(width) + "x" + std::to_string(height) + ".rgba"), std::ios::binary); + for (int i = 0; i < poolSize; ++i) { + const auto frame = makeFrame(width, height, i); + output.write(reinterpret_cast(frame.data()), static_cast(frame.size())); + } + if (!output) + throw std::runtime_error("cannot write the frames"); + } +} + +} // namespace + +int main(int argc, char** argv) { + try { + if (argc == 3 && std::string_view(argv[1]) == "--dump-frames") { // before the engine: no display needed + dumpFrames(argv[2]); + return 0; + } + BenchFrontend::initialize(); // CEF: a child process runs and ends here, before the arguments are read + std::vector positional; + int seconds = 5; + for (int i = 1; i < argc; ++i) { + const std::string argument = argv[i]; + if (argument == "--seconds" && i + 1 < argc) + seconds = std::stoi(argv[++i]); + else + positional.push_back(argument); + } + if (positional.empty() || positional.size() > 2 || seconds <= 0) + throw std::runtime_error("usage: image_stream_bench [] [--seconds N] | --dump-frames "); +#ifdef WEBFRONT_BENCH_SHM + SharedFrames shared; + sharedFrames = &shared; + // Read by the extension in the web process, which inherits this process's environment. + setenv("WEBFRONT_BENCH_SHM_NAME", shared.name.c_str(), 1); + setenv("WEBFRONT_BENCH_SHM_SIZE", std::to_string(SharedFrames::slotSize).c_str(), 1); +#endif + bool reported = false; + { + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::absolute(positional[0])}); + Bench bench(app, seconds, positional.size() > 1 ? positional[1] : ""); + app.show("bench.html"); + reported = bench.reported; + } + if (!reported) + throw std::runtime_error("the benchmark page closed without a report"); + return 0; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} diff --git a/test/web/ImageStreamWebExtension.cpp b/test/web/ImageStreamWebExtension.cpp new file mode 100644 index 00000000..43da8c02 --- /dev/null +++ b/test/web/ImageStreamWebExtension.cpp @@ -0,0 +1,67 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/web +// Role: Prototype WebKitGTK web process extension exposing a host's shared memory to the page (#769). +// Thread: ui-loop | Alloc: bounded +// LLM: measurement prototype only; no origin or frame filtering, never ship it as is + +// Loaded by image_stream_bench into the web process: window.wfSharedSlot(slot, length) returns the first bytes of a +// slot of the mapping. The object's name and slot size come from the environment the web process inherits. It needs the +// development sandbox mode: a sandboxed web process does not see the host's shared memory object. + +#include +#include +#include + +#include +#include +#include +#include + +namespace { +constexpr int slots = 3; +unsigned char* mapping = nullptr; +std::size_t slotSize = 0; + +// One copy, in the web process, into memory JavaScriptCore allocated. jsc_value_new_array_buffer() over the mapping itself +// would avoid it, but WebKitGTK 2.52 kills the web process when a page receives it ("Disabling Primitive gigacage is +// forbidden"): the negative result recorded in docs/IMAGE_STREAMS.md. +JSCValue* sharedSlot(double slot, double length, gpointer) { + auto* context = jsc_context_get_current(); + if (!mapping || slot < 0 || slot >= slots || length < 0 || length > static_cast(slotSize)) + return jsc_value_new_null(context); + const auto bytes = static_cast(length); + auto* array = jsc_value_new_typed_array(context, JSC_TYPED_ARRAY_UINT8, bytes); + gsize count = 0; + void* data = jsc_value_typed_array_get_data(array, &count); + std::memcpy(data, mapping + static_cast(slot) * slotSize, std::min(bytes, count)); + return array; +} + +void windowCleared(WebKitScriptWorld* world, WebKitWebPage*, WebKitFrame* frame, gpointer) { + auto* context = webkit_frame_get_js_context_for_script_world(frame, world); + auto* function = jsc_value_new_function(context, "wfSharedSlot", G_CALLBACK(sharedSlot), nullptr, nullptr, JSC_TYPE_VALUE, 2, G_TYPE_DOUBLE, G_TYPE_DOUBLE); + jsc_context_set_value(context, "wfSharedSlot", function); + g_object_unref(function); + g_object_unref(context); +} +} // namespace + +extern "C" G_MODULE_EXPORT void webkit_web_process_extension_initialize(WebKitWebProcessExtension*) { + const char* name = std::getenv("WEBFRONT_BENCH_SHM_NAME"); + const char* size = std::getenv("WEBFRONT_BENCH_SHM_SIZE"); + if (!name || !size) + return; + slotSize = std::strtoull(size, nullptr, 10); + const int fd = shm_open(name, O_RDONLY, 0600); + if (fd < 0) + return; + auto* mapped = mmap(nullptr, slotSize * slots, PROT_READ, MAP_SHARED, fd, 0); + close(fd); + if (mapped == MAP_FAILED) + return; + mapping = static_cast(mapped); + g_signal_connect(webkit_script_world_get_default(), "window-object-cleared", G_CALLBACK(windowCleared), nullptr); +} diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index b99ae920..26086c54 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -646,13 +646,6 @@ class BrowserIntegrationTest { webFront->cppFunction("setEcho", [](const set& value) { return value; }); - // For the measurement of test/web/suite/bench/image-streams.mjs: a frame there and back, and its report. - webFront->cppFunction("bytesEcho", [](const vector& value) { - return value; - }); - webFront->cppFunction("benchReport", [](const string& report) { - std::cout << "IMAGE-STREAMS " << report << std::endl; - }); webFront->cppFunction("dequeEcho", [](const deque& value) { return value; }); diff --git a/test/web/image-stream/bench.html b/test/web/image-stream/bench.html new file mode 100644 index 00000000..51d3957f --- /dev/null +++ b/test/web/image-stream/bench.html @@ -0,0 +1,10 @@ + + +Image stream measurement + +

Starting

+ + + + + diff --git a/test/web/image-stream/bench.js b/test/web/image-stream/bench.js new file mode 100644 index 00000000..1d83eb03 --- /dev/null +++ b/test/web/image-stream/bench.js @@ -0,0 +1,175 @@ +// The page of image_stream_bench (test/web/ImageStreamBenchmark.cpp, docs/IMAGE_STREAMS.md): it draws every frame the +// host sends, whatever the track, acknowledges it, then measures the engine's WebCodecs decoder. +(async () => { + const canvas = document.getElementById('screen'), context = canvas.getContext('2d'), status = document.getElementById('status'); + const call = name => webFront.cppFunction(name); + let width = 0, height = 0, jpeg = false, failure = null, queue = Promise.resolve(), drawnFrame = null; + + /** Draws one frame and tells the host. getImageData makes the engine finish the drawing before the clock is read. */ + function show(sequence, bytes) { + queue = queue.then(async () => { + const start = performance.now(); + if (jpeg) { + const bitmap = await createImageBitmap(new Blob([bytes], {type: 'image/jpeg'})); + context.drawImage(bitmap, 0, 0); + bitmap.close(); + } else + context.putImageData(new ImageData(new Uint8ClampedArray(bytes.buffer, bytes.byteOffset, bytes.byteLength), width, height), 0, 0); + drawnFrame = context.getImageData(0, 0, 1, 1).data; + call('benchDrawn')(sequence, performance.now() - start).catch(error => { failure = error; }); + }).catch(error => { failure = error; }); + } + window.bench = { + frame: show, + // The shared memory track: wfSharedSlot is defined by the benchmark's WebKitGTK web process extension. + shared: (sequence, slot, length) => show(sequence, window.wfSharedSlot(slot, length)) + }; + + /** Reads the streamed route: for each frame, a 32-bit length, a 32-bit sequence number and the bytes. */ + async function readRoute() { + const response = await fetch('/frames/', {cache: 'no-store'}); + const reader = response.body.getReader(); + const header = new Uint8Array(8); + let frame = null, filled = 0, sequence = 0; + for (;;) { + const {value, done} = await reader.read(); + if (done) return; + for (let at = 0; at < value.length;) { + const target = frame ?? header; + const count = Math.min(target.length - filled, value.length - at); + target.set(value.subarray(at, at + count), filled); + filled += count; + at += count; + if (filled < target.length) continue; + filled = 0; + if (frame) { + show(sequence, frame); + frame = null; + } else { + const view = new DataView(header.buffer); + sequence = view.getUint32(4, true); + frame = new Uint8Array(view.getUint32(0, true)); + } + } + } + } + + async function encodePool() { + const encoder = new OffscreenCanvas(width, height), surface = encoder.getContext('2d'); + for (let index = 0; index < 16; ++index) { + const bytes = await call('benchFrame')(index); + surface.putImageData(new ImageData(new Uint8ClampedArray(bytes.slice().buffer), width, height), 0, 0); + const blob = await encoder.convertToBlob({type: 'image/jpeg', quality: 0.85}); + await call('benchEncoded')(new Uint8Array(await blob.arrayBuffer())); + } + } + + async function measureTrack(config, track, size, fps) { + [width, height] = size; + canvas.width = width; + canvas.height = height; + jpeg = track.startsWith('jpeg'); + failure = null; + status.textContent = `${track} ${width}x${height} at ${fps || 'maximum'} fps`; + await call('benchPrepare')(track, width, height, fps); + if (jpeg && !config.hostEncodes) await encodePool(); + if (track === 'raw-shared' && typeof window.wfSharedSlot !== 'function') + return {error: 'the web process extension is not loaded'}; + await call('benchStart')(); + const reading = track.endsWith('route') ? readRoute() : Promise.resolve(); + const result = JSON.parse(await call('benchMeasure')()); + await reading; + await queue; + if (failure) return {error: String(failure)}; + return result; + } + + /** Encodes frames with the engine's encoder, then times each frame from decode() to its output, one at a time. */ + async function measureCodec(codec, [w, h]) { + if (typeof VideoDecoder === 'undefined' || typeof VideoEncoder === 'undefined') + return {error: `no ${typeof VideoDecoder === 'undefined' ? 'VideoDecoder' : 'VideoEncoder'}`}; + const settings = {codec, width: w, height: h, bitrate: w * h * 4, framerate: 30, latencyMode: 'realtime'}; + if (codec.startsWith('avc1')) settings.avc = {format: 'annexb'}; + if (!(await VideoDecoder.isConfigSupported({codec, codedWidth: w, codedHeight: h})).supported) + return {error: 'decoding not supported'}; + if (!(await VideoEncoder.isConfigSupported(settings)).supported) + return {error: 'decoding supported, no encoder to produce a test stream'}; + const chunks = []; + let broken = null; + const encoder = new VideoEncoder({output: chunk => chunks.push(chunk), error: error => { broken = error; }}); + encoder.configure(settings); + const source = new OffscreenCanvas(w, h), surface = source.getContext('2d'); + for (let index = 0; index < 90 && !broken; ++index) { + surface.fillStyle = `hsl(${index * 4}, 60%, 40%)`; + surface.fillRect(0, 0, w, h); + surface.fillStyle = 'white'; + for (let x = 0; x < 40; ++x) surface.fillRect((x * 97 + index * 11) % w, (x * 53) % h, 24, 24); + const frame = new VideoFrame(source, {timestamp: index * 33333}); + encoder.encode(frame, {keyFrame: index === 0}); + frame.close(); + if (encoder.encodeQueueSize > 4) await new Promise(resolve => encoder.addEventListener('dequeue', resolve, {once: true})); + } + await encoder.flush(); + encoder.close(); + if (broken) throw broken; + let ready = null; + const decoder = new VideoDecoder({ + output: frame => { context.drawImage(frame, 0, 0); frame.close(); ready?.(); }, + error: error => { broken = error; ready?.(); } + }); + decoder.configure({codec, codedWidth: w, codedHeight: h, optimizeForLatency: true}); + canvas.width = w; + canvas.height = h; + const times = []; + let late = 0, bytes = 0; + for (const chunk of chunks) { + const start = performance.now(); + const output = new Promise(resolve => { ready = () => resolve(true); }); + decoder.decode(chunk); + // A decoder that holds frames back gives nothing until it has more input: count it instead of waiting. + if (await Promise.race([output, new Promise(resolve => setTimeout(() => resolve(false), 250))])) { + context.getImageData(0, 0, 1, 1); + times.push(performance.now() - start); + } else + ++late; + bytes += chunk.byteLength; + if (broken) throw broken; + if (late > 5) break; + } + decoder.close(); + times.sort((a, b) => a - b); + const at = p => times.length ? Math.round(times[Math.floor(p * (times.length - 1))] * 100) / 100 : null; + return {frames: times.length, heldBack: late, chunkBytes: Math.round(bytes / chunks.length), decodeDrawMs50: at(0.5), decodeDrawMs95: at(0.95)}; + } + + await webFront.ready; + const config = JSON.parse(await call('benchConfig')()); + const report = {userAgent: navigator.userAgent, cores: config.cores, secondsPerCase: config.seconds, + hostEncodes: config.hostEncodes, tracks: {}, codecs: {}}; + const sizes = [[960, 720], [1920, 1080]]; + for (const size of sizes) { + for (const track of config.tracks.split(',')) + for (const fps of [30, 0]) { + const key = `${track} ${size.join('x')} ${fps ? fps + 'fps' : 'max'}`; + try { + report.tracks[key] = await measureTrack(config, track, size, fps); + } catch (error) { + report.tracks[key] = {error: String(error)}; + } + await call('benchProgress')(`${key} ${JSON.stringify(report.tracks[key])}`); + } + for (const [name, codec] of [['vp8', 'vp8'], ['vp9', 'vp09.00.31.08'], ['h264', 'avc1.42002a']]) { + status.textContent = `${name} ${size.join('x')}`; + try { + report.codecs[`${name} ${size.join('x')}`] = await measureCodec(codec, size); + } catch (error) { + report.codecs[`${name} ${size.join('x')}`] = {error: String(error)}; + } + } + } + await call('benchReport')(JSON.stringify(report)); + status.textContent = 'Done'; +})().catch(error => { + console.error(error); + document.getElementById('status').textContent = String(error); +}); diff --git a/test/web/image-stream/host-encoders.sh b/test/web/image-stream/host-encoders.sh new file mode 100644 index 00000000..2bb9e2a0 --- /dev/null +++ b/test/web/image-stream/host-encoders.sh @@ -0,0 +1,43 @@ +#!/usr/bin/env bash +# Times the host-side encoders ffmpeg offers on the frames of image_stream_bench (#769, docs/IMAGE_STREAMS.md). +# host-encoders.sh +# One line per size and encoder: wall and CPU milliseconds per frame, and bytes per frame. An encoder ffmpeg does not have, +# or cannot open on this machine, is reported as unavailable: that is a result too. Hardware encoder devices are listed. +set -euo pipefail +bench=$1 work=$2 repeats=10 +echo "ENCODER-DEVICES $(ls /dev/nvhost-msenc /dev/v4l2-nvenc /dev/nvidia0 /dev/dri/renderD* 2>/dev/null | tr '\n' ' ')" +if command -v gst-inspect-1.0 >/dev/null; then + echo "ENCODER-GSTREAMER nvv4l2h264enc: $(gst-inspect-1.0 nvv4l2h264enc >/dev/null 2>&1 && echo present || echo absent)" +fi +command -v ffmpeg >/dev/null || { echo "ENCODER ffmpeg: unavailable (not installed)"; exit 0; } +"$bench" --dump-frames "$work" +ffmpeg -version | head -1 +for size in 960x720 1920x1080; do + for encoder in "mjpeg -q:v 4" "libx264 -preset ultrafast -tune zerolatency" "libvpx -deadline realtime -cpu-used 8 -b:v 4M" \ + "libvpx-vp9 -deadline realtime -cpu-used 8 -row-mt 1 -b:v 4M" "h264_nvenc -preset p1 -tune ull" "h264_v4l2m2m" \ + "h264_vaapi"; do + read -r name options <<< "$encoder" + input=(-f rawvideo -pixel_format rgba -video_size "$size" -framerate 30 -stream_loop $((repeats - 1)) -i "$work/$size.rgba") + filter=(-pix_fmt yuv420p) + [[ $name == mjpeg ]] && filter=(-pix_fmt yuvj420p) + device=() + if [[ $name == h264_vaapi ]]; then + device=(-vaapi_device /dev/dri/renderD128) + filter=(-vf format=nv12,hwupload) + fi + output="$work/$size-$name.bin" + container=h264 + [[ $name == mjpeg ]] && container=mjpeg + [[ $name == libvpx* ]] && container=ivf + # shellcheck disable=SC2086 # the options are several words + if log=$(ffmpeg -hide_banner -nostdin -y -benchmark "${device[@]}" "${input[@]}" "${filter[@]}" -c:v "$name" $options \ + -f "$container" "$output" 2>&1); then + frames=$((16 * repeats)) + read -r user system real <<< "$(sed -n 's/^bench: utime=\([0-9.]*\)s stime=\([0-9.]*\)s rtime=\([0-9.]*\)s.*/\1 \2 \3/p' <<< "$log")" + awk -v s="$size" -v e="$name" -v u="$user" -v y="$system" -v r="$real" -v n="$frames" -v b="$(wc -c < "$output")" \ + 'BEGIN { printf "ENCODER %s %s: wall %.2f ms/frame, cpu %.2f ms/frame, %d bytes/frame\n", s, e, r * 1000 / n, (u + y) * 1000 / n, b / n }' + else + echo "ENCODER $size $name: unavailable ($(tail -n 1 <<< "$log"))" + fi + done +done diff --git a/test/web/suite/bench/image-streams.mjs b/test/web/suite/bench/image-streams.mjs deleted file mode 100644 index 915b6455..00000000 --- a/test/web/suite/bench/image-streams.mjs +++ /dev/null @@ -1,61 +0,0 @@ -// A measurement, not a test: not part of the suite. To run it, add `import '../bench/image-streams.mjs';` at the end of -// specs/webfront-specs.mjs (keep the other specs, which the test program requires), run the WebFront browser integration test and read the "IMAGE-STREAMS" line of its output. -// See docs/IMAGE_STREAMS.md. -const sizes = [[960, 720], [1920, 1080]]; -const iterations = 30; - -/** A frame with gradients, edges and some noise: neither the best nor the worst case of an image codec. */ -function frame(width, height) { - const pixels = new Uint8ClampedArray(width * height * 4); - let seed = 1; - for (let y = 0, i = 0; y < height; ++y) - for (let x = 0; x < width; ++x, i += 4) { - seed = (seed * 48271) % 2147483647; - const check = ((x >> 5) + (y >> 5)) & 1; - pixels[i] = (x * 255 / width) | 0; - pixels[i + 1] = check ? 220 : 30; - pixels[i + 2] = ((y * 255 / height) | 0) ^ (seed & 7); - pixels[i + 3] = 255; - } - return new ImageData(pixels, width, height); -} -async function mean(action) { - await action(); // warm-up - const start = performance.now(); - for (let n = 0; n < iterations; ++n) await action(); - return Math.round((performance.now() - start) / iterations * 100) / 100; -} - -describe('Image stream measurement', () => { - it('reports', async () => { - const echo = webFront.cppFunction('bytesEcho'); - const report = {userAgent: navigator.userAgent, cores: navigator.hardwareConcurrency, codecs: {}, sizes: {}}; - for (const [name, codec] of [['vp8', 'vp8'], ['vp9', 'vp09.00.10.08'], ['h264', 'avc1.42001f']]) { - report.codecs[name] = typeof VideoDecoder === 'undefined' ? 'no VideoDecoder' - : (await VideoDecoder.isConfigSupported({codec, codedWidth: 960, codedHeight: 720})).supported; - } - for (const [width, height] of sizes) { - const image = frame(width, height), canvas = new OffscreenCanvas(width, height), context = canvas.getContext('2d'); - context.putImageData(image, 0, 0); - const jpeg = new Uint8Array(await (await canvas.convertToBlob({type: 'image/jpeg', quality: 0.85})).arrayBuffer()); - const raw = new Uint8Array(image.data.buffer); - // getImageData after drawing makes the engine finish the drawing before the clock is read. - const drawn = () => context.getImageData(0, 0, 1, 1); - report.sizes[`${width}x${height}`] = { - rawBytes: raw.length, - jpegBytes: jpeg.length, - rawEchoMs: await mean(() => echo(raw)), - jpegEchoMs: await mean(() => echo(jpeg)), - rawDrawMs: await mean(async () => { context.putImageData(image, 0, 0); drawn(); }), - jpegDecodeDrawMs: await mean(async () => { - const bitmap = await createImageBitmap(new Blob([jpeg], {type: 'image/jpeg'})); - context.drawImage(bitmap, 0, 0); - bitmap.close(); - drawn(); - }), - }; - } - console.log('IMAGE-STREAMS ' + JSON.stringify(report)); - await webFront.cppFunction('benchReport')(JSON.stringify(report)); - }, 120000); -}); From 8e56b53d1d9aadaf92d0b0c5807d36c0451348bb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:54:07 +0100 Subject: [PATCH 03/20] Add the image stream example: JPEG frames on demand, typed-array pixels as fallback (#769) --- AGENTS.md | 2 +- examples/CMakeLists.txt | 10 +- examples/image-stream/ImageStream.cpp | 28 +++ examples/image-stream/ImageStreamHost.hpp | 205 ++++++++++++++++++++++ test/cmake/CheckNewcomerDocs.cmake | 4 +- test/web/CMakeLists.txt | 21 +++ test/web/ImageStreamExampleTest.cpp | 50 ++++++ 7 files changed, 316 insertions(+), 4 deletions(-) create mode 100644 examples/image-stream/ImageStream.cpp create mode 100644 examples/image-stream/ImageStreamHost.hpp create mode 100644 test/web/ImageStreamExampleTest.cpp diff --git a/AGENTS.md b/AGENTS.md index 100e46d5..9ba93659 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,7 @@ The README introduces WebFront through the Game of Life walkthrough, demonstrati - `include/webfront/system/`: layered virtual filesystems and the embedded web resources, a closed list guarded by the `MinimalCoreAssets` CTest case (normative list and 150 KiB decoded budget in ADR-016; changing it means amending the ADR and `test/cmake/CheckMinimalCoreAssets.cmake` together). - `include/webfront/frontend/`: system-browser, CEF, optional Windows WebView2 and macOS WKWebView frontend adapters. - `docs/DISTRIBUTION.md`: `find_package(WebFront)` (`cmake/WebFrontInstall.cmake`, pins in `cmake/WebFrontDependencies.cmake`), the vcpkg port and Conan recipe in `cmake/packaging/`, `webfront_package()`, the SBOM and the optional updater `include/webfront/components/update/` (ADR-028; never write cryptography there). -- `examples/`: the default build includes Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). The standalone [PTY example](docs/PTY.md) has its own CMake entry point. +- `examples/`: the default build includes Hello World (`hello-world/`), the host loop (`host-loop/`: an application that keeps its own loop, `app.start()` or a host thread beside a native window; it ray-traces a Boing Ball on the CPU or with an optional CUDA unit, see `docs/HOST_LOOP_EXAMPLE.md`), the image stream (`image-stream/`: images of the host in the page, JPEG frames or typed-array pixels, `docs/IMAGE_STREAMS.md`) and Game of Life (`life/`, with console, developer and embedded stages, plus the `life/react/` variant with a C++ panel inside React). The standalone [PTY example](docs/PTY.md) has its own CMake entry point. - `js/core/`: readable browser bridge, fallback and bootstrap loader compiled into `include/webfront/`, plus the embedding CMake modules; `js/developer/`: developer environment (its terminal and `wf`), the wf scripts that build it (`scripts/`), build and publication tools. The repository is itself a `wf` project (`js/developer/webfront.project.json` and its lock, selected with `--manifest-dir js/developer`): the environment builds itself, and its pure JavaScript specs (`test/developer/`) run with `wf test`. Production C++ remains header-only in `include/webfront/`. - `js/developer/starters/`: the sources of the `app` and `store` starters (`store` receives copies of `js/store/` when the environment is built) and `agent-guide.md`, the `AGENTS.md` that `wf create` puts beside a starter and that `webfront_write_agent_guide()` (`cmake/WebFrontAgentGuide.cmake`) writes in a consuming project. - `js/services/`: optional `@webfront/services` package, the browser side of the system services (ADR-020; a skeleton so far), built like `@webfront/react` by `wf run services-package`; outside the core's embedded resource list. diff --git a/examples/CMakeLists.txt b/examples/CMakeLists.txt index 227ec410..d6ffe936 100644 --- a/examples/CMakeLists.txt +++ b/examples/CMakeLists.txt @@ -1,4 +1,5 @@ -# Three examples: the minimal application, the successive Game of Life stages and a host application that keeps its loop. +# Four examples: the minimal application, the successive Game of Life stages, a host application that keeps its loop and +# images of the host shown in the page. include(Frontends) # The Life examples use NativeOrBrowserFrontend: the native window when its engine is built and a session exists, @@ -35,6 +36,13 @@ if(WEBFRONT_ENABLE_TESTING) set_tests_properties(HostLoopCaptureModes PROPERTIES TIMEOUT 15 LABELS fast) endif() +# Images of the host shown in the page (docs/IMAGE_STREAMS.md): JPEG frames when a JPEG library is found, raw pixels otherwise. +add_executable(WebFrontImageStream image-stream/ImageStream.cpp) +target_link_libraries(WebFrontImageStream PRIVATE WebFront WebFront_warnings WebFront_options) +webfront_setup_frontends_for_target(WebFrontImageStream) +include(ImageStreamJpeg) +webfront_link_image_stream_jpeg(WebFrontImageStream WEBFRONT_EXAMPLE_JPEG) + # The simulation can be explored before adding a UI or enabling a native engine. add_executable(WebFrontLifeConsole life/LifeConsole.cpp) target_link_libraries(WebFrontLifeConsole PRIVATE WebFront_warnings WebFront_options) diff --git a/examples/image-stream/ImageStream.cpp b/examples/image-stream/ImageStream.cpp new file mode 100644 index 00000000..309b4385 --- /dev/null +++ b/examples/image-stream/ImageStream.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — examples +// Role: Shows a stream of images of the host in the page: JPEG frames, or pixels with --raw or without a JPEG library. +// Thread: multi-thread | Alloc: unrestricted +// LLM: example; see ImageStreamHost.hpp and docs/IMAGE_STREAMS.md + +#include "../PortOption.hpp" +#include "ImageStreamHost.hpp" + +#include + +int main(int argc, char** argv) { + if (!webfront::demo::applyPortOption(argc, argv)) + return 2; + const bool raw = argc == 2 && std::string_view(argv[1]) == "--raw"; + if (argc > 1 && !raw) { + std::cerr << "usage: WebFrontImageStream [--raw] [--port ]\n"; + return 2; + } + imagestream::Source source; // before the application: its callbacks read it + webfront::WebFront app; + imagestream::serve(app, source, raw); + app.show(); + return 0; +} diff --git a/examples/image-stream/ImageStreamHost.hpp b/examples/image-stream/ImageStreamHost.hpp new file mode 100644 index 00000000..f714f3c6 --- /dev/null +++ b/examples/image-stream/ImageStreamHost.hpp @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — examples +// Role: A source of images and the callbacks and page that show them: JPEG frames, or pixels in a typed array. +// Thread: multi-thread | Alloc: unrestricted +// LLM: example; the source must outlive the application that registers its callbacks + +#pragma once + +// The track docs/IMAGE_STREAMS.md selects. The page asks for an image only once the previous one is drawn, and gets the +// newest one: what the page has no time for is skipped, nothing queues up, however slow the engine. +// +// image.options() -> [the host encodes JPEG, the application asks for pixels] +// image.next(after, jpeg) -> [sequence, is JPEG, width, height, bytes], once an image newer than `after` exists +// image.shown(sequence, jpeg, rgb) the page drew it; rgb is the pixel at (4, 4) as 0xRRGGBB +// +// The bytes are a JPEG file when `is JPEG`, otherwise width * height * 4 bytes, R, G, B, A. Without a JPEG library in the +// build (WEBFRONT_EXAMPLE_JPEG) or without createImageBitmap in the page, the pixels are sent. + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#ifdef WEBFRONT_EXAMPLE_JPEG +// clang-format off +#include +#include +#include +// clang-format on +#endif + +namespace imagestream { + +inline constexpr int width = 960; +inline constexpr int height = 720; + +#ifdef WEBFRONT_EXAMPLE_JPEG +inline constexpr bool encodesJpeg = true; + +/// JPEG at quality 0.85 of an RGBA image. libjpeg's default error handler ends the process, which only memory exhaustion +/// reaches here. +inline std::vector encodeJpeg(const std::vector& rgba) { + jpeg_compress_struct info{}; + jpeg_error_mgr errors{}; + info.err = jpeg_std_error(&errors); + jpeg_create_compress(&info); + unsigned char* output = nullptr; + unsigned long size = 0; + jpeg_mem_dest(&info, &output, &size); + info.image_width = width; + info.image_height = height; + info.input_components = 3; + info.in_color_space = JCS_RGB; + jpeg_set_defaults(&info); + jpeg_set_quality(&info, 85, TRUE); + jpeg_start_compress(&info, TRUE); + std::vector row(static_cast(width) * 3); + while (info.next_scanline < info.image_height) { + const auto* source = rgba.data() + static_cast(info.next_scanline) * width * 4; + for (std::size_t x = 0; x < static_cast(width); ++x) + for (std::size_t channel = 0; channel < 3; ++channel) + row[3 * x + channel] = source[4 * x + channel]; + auto* line = row.data(); + jpeg_write_scanlines(&info, &line, 1); + } + jpeg_finish_compress(&info); + std::vector result(output, output + size); + jpeg_destroy_compress(&info); + std::free(output); + return result; +} +#else +inline constexpr bool encodesJpeg = false; +inline std::vector encodeJpeg(const std::vector&) { + return {}; +} +#endif + +/// Stands for a camera: draws 30 images a second on its own thread, a bar sweeping a gradient under a red corner. +class Source { +public: + struct Image { + std::uint32_t sequence = 0; + std::vector pixels; + }; + + Source() + : worker([this](std::stop_token stopping) { + run(stopping); + }) { } + + [[nodiscard]] std::shared_ptr latest() const { + std::scoped_lock lock(mutex); + return image; + } + +private: + mutable std::mutex mutex; + std::shared_ptr image; + std::jthread worker; // last: stopped and joined before what it writes is destroyed + + void run(std::stop_token stopping) { + auto tick = std::chrono::steady_clock::now(); + for (std::uint32_t sequence = 1; !stopping.stop_requested(); ++sequence) { + auto next = std::make_shared(); + next->sequence = sequence; + next->pixels.resize(static_cast(width) * height * 4); + const int bar = static_cast(sequence * 8 % width); + std::size_t at = 0; + for (int y = 0; y < height; ++y) + for (int x = 0; x < width; ++x, at += 4) { + const bool corner = x < 32 && y < 32; + const bool swept = x >= bar && x < bar + 24; + next->pixels[at] = static_cast(corner || swept ? 255 : x * 255 / width); + next->pixels[at + 1] = static_cast(corner ? 0 : swept ? 255 : y * 255 / height); + next->pixels[at + 2] = static_cast(corner ? 0 : swept ? 255 : 96); + next->pixels[at + 3] = 255; + } + { + std::scoped_lock lock(mutex); + image = std::move(next); + } + tick += std::chrono::milliseconds(33); + std::this_thread::sleep_until(tick); + } + } +}; + +inline constexpr std::string_view page = R"js( +(async () => { + const call = (name, ...args) => webFront.cppFunction(name)(...args); + const status = document.body.appendChild(document.createElement("p")); + const canvas = document.body.appendChild(document.createElement("canvas")); + canvas.style.maxWidth = "100%"; + const context = canvas.getContext("2d"); + const [hostEncodes, forceRaw] = await call("image.options"); + let jpeg = hostEncodes && !forceRaw && typeof createImageBitmap === "function"; + let last = 0, drawn = 0; + const started = performance.now(); + for (;;) { + const [sequence, compressed, width, height, bytes] = await call("image.next", last, jpeg); + last = sequence; + if (canvas.width !== width || canvas.height !== height) { + canvas.width = width; + canvas.height = height; + } + if (compressed) { + try { + const bitmap = await createImageBitmap(new Blob([bytes], {type: "image/jpeg"})); + context.drawImage(bitmap, 0, 0); + bitmap.close(); + } catch (error) { + console.warn("JPEG decoding failed, asking for pixels", error); + jpeg = false; + continue; + } + } else + context.putImageData(new ImageData(new Uint8ClampedArray(bytes.buffer, bytes.byteOffset, bytes.byteLength), width, height), 0, 0); + const [r, g, b] = context.getImageData(4, 4, 1, 1).data; + await call("image.shown", sequence, compressed, (r << 16) | (g << 8) | b); + status.textContent = `${compressed ? "JPEG" : "pixels"}, image ${sequence}, ` + + `${(++drawn * 1000 / (performance.now() - started)).toFixed(1)} drawn per second`; + } +})().catch(error => console.error(error)); +)js"; + +using Frame = std::tuple>; + +/// Registers the callbacks and adds the page to each browser. `shown` hears of every image the page drew. +template +void serve(App& app, const Source& source, bool forceRaw, std::function shown = {}) { + app.cppFunction("image.options", [forceRaw] { + return std::tuple{encodesJpeg, forceRaw}; + }); + app.cppFunction("image.next", [&app, &source](std::uint32_t after, bool jpeg) -> webfront::ResultTask { + // Waiting suspends this call only; leaving the page cancels it. + auto image = source.latest(); + while (!image || image->sequence <= after) { + co_await app.resumeAfter(std::chrono::milliseconds(2)); + image = source.latest(); + } + const bool compressed = jpeg && encodesJpeg; + co_return Frame{image->sequence, compressed, width, height, compressed ? encodeJpeg(image->pixels) : image->pixels}; + }); + app.cppFunction("image.shown", [shown](std::uint32_t sequence, bool jpeg, std::uint32_t colour) { + if (shown) + shown(sequence, jpeg, colour); + }); + app.onUIStarted([](typename App::UI ui) { + ui.addScript(page); + }); +} + +} // namespace imagestream diff --git a/test/cmake/CheckNewcomerDocs.cmake b/test/cmake/CheckNewcomerDocs.cmake index 5fe20c84..bde43426 100644 --- a/test/cmake/CheckNewcomerDocs.cmake +++ b/test/cmake/CheckNewcomerDocs.cmake @@ -85,8 +85,8 @@ foreach(target HelloWorld WebFrontLifeConsole WebFrontLifeDeveloper WebFrontLife endforeach() string(REGEX MATCHALL "add_executable\\(" targets "${examples}") list(LENGTH targets target_count) -if(NOT target_count EQUAL 6) - list(APPEND failures "Only Hello World, the host loop, the three Life stages and the React adapter variant should be built") +if(NOT target_count EQUAL 7) + list(APPEND failures "Only Hello World, the host loop, the image stream, the three Life stages and the React adapter variant should be built") endif() foreach(command "wf create life" "wf init" "wf install react@19.3.1 react-dom@19.3.1" "wf dev ui/main.tsx" "wf check" "wf test" "wf embed ui/main.tsx --output generated/LifeUI.hpp") _require("${readme}" "${command}" "developer-terminal walkthrough") diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 76ef384c..81a91901 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -171,6 +171,27 @@ if(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_OPTION} webfront_provision_registry(_registry_archives "${CMAKE_CURRENT_SOURCE_DIR}/registry-packages.json" "${CMAKE_BINARY_DIR}/registry-archives") endif() +# The page of the image stream example (docs/IMAGE_STREAMS.md) draws images in the engine, JPEG and typed array. +if(_browser_tests_available) + webfront_add_test_program(image_stream_example ImageStreamExampleTest.cpp WITH_WEBTEST) + include(ImageStreamJpeg) + webfront_link_image_stream_jpeg(image_stream_example WEBFRONT_EXAMPLE_JPEG) + # Without a display, WebKitGTK and CEF run under the display runner the other browser tests use. + webfront_optional_window_test_runner(_image_stream_runner _image_stream_windows) + if(_image_stream_windows) + foreach(_mode jpeg raw) + set(_arguments) + if(_mode STREQUAL "raw") + set(_arguments --raw) + endif() + add_test(NAME ImageStreamExample-${_mode} + COMMAND ${_image_stream_runner} $ ${_arguments}) + webfront_set_browser_test_properties(ImageStreamExample-${_mode} "${CMAKE_CURRENT_SOURCE_DIR}" 90) + webfront_use_own_profile(ImageStreamExample-${_mode} image-stream) + endforeach() + endif() +endif() + # A copy of the sources that the scripts of the repository run on (#315); the registry and the environment are built in it. set(_self_project "${CMAKE_CURRENT_BINARY_DIR}/self-build-project") set(_registry "${_self_project}/build-registry") diff --git a/test/web/ImageStreamExampleTest.cpp b/test/web/ImageStreamExampleTest.cpp new file mode 100644 index 00000000..94df5bf3 --- /dev/null +++ b/test/web/ImageStreamExampleTest.cpp @@ -0,0 +1,50 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/web +// Role: Runs the image stream example's page in a real engine and checks the images it draws, in both formats. +// Thread: ui-loop | Alloc: unrestricted +// LLM: real-browser test; the CTest timeout ends a page that draws nothing + +#include "../../examples/image-stream/ImageStreamHost.hpp" + +#include +#include + +#ifndef WEBFRONT_TEST_FRONTEND + #error "WEBFRONT_TEST_FRONTEND names the browser test frontend" +#endif + +int main(int argc, char** argv) { + try { + WEBFRONT_TEST_FRONTEND::initialize(); // CEF: a child process runs and ends here + const bool raw = argc == 2 && std::string_view(argv[1]) == "--raw"; + const bool expected = !raw && imagestream::encodesJpeg; + constexpr int wanted = 5; + int frames = 0; + bool failed = false; + std::uint32_t previous = 0; + { + imagestream::Source source; + webfront::BasicWFWithFrontend, WEBFRONT_TEST_FRONTEND> app; + imagestream::serve(app, source, raw, [&](std::uint32_t sequence, bool jpeg, std::uint32_t colour) { + // The red corner, within what JPEG changes; images arrive in order, never twice. + const bool red = (colour >> 16) > 200 && ((colour >> 8) & 0xff) < 60 && (colour & 0xff) < 60; + if (!red || jpeg != expected || sequence <= previous) { + std::cerr << "unexpected image " << sequence << ", jpeg " << jpeg << ", colour " << std::hex << colour << std::dec << '\n'; + failed = true; + } + previous = sequence; + if (++frames == wanted) + app.requestClose(); + }); + app.show(); + } + std::cout << frames << (expected ? " JPEG images" : " raw images") << " drawn\n"; + return !failed && frames >= wanted ? 0 : 1; + } catch (const std::exception& error) { + std::cerr << error.what() << '\n'; + return 1; + } +} From 02764f2c5098059663288b87f9922bd950262a17 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:54:07 +0100 Subject: [PATCH 04/20] Record the image stream measurement on dispatch: WebView2, WKWebView and Jetson (#769) --- .github/scripts/jetson-orin.sh | 10 ++++++ .github/workflows/BuildAndTest.yml | 49 ++++++++++++++++++++++++++++++ docs/JETSON_RUNNER.md | 2 ++ 3 files changed, 61 insertions(+) diff --git a/.github/scripts/jetson-orin.sh b/.github/scripts/jetson-orin.sh index 58a0dc3c..6f5a7ec1 100755 --- a/.github/scripts/jetson-orin.sh +++ b/.github/scripts/jetson-orin.sh @@ -50,4 +50,14 @@ cmake -S . -B build-jetson-webkitgtk "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=O cmake --build build-jetson-webkitgtk --target webtest developer_integration webfront-wf --parallel 2 ctest --test-dir build-jetson-webkitgtk -L web-integration --output-on-failure --no-tests=error \ --parallel 2 --output-junit webkitgtk-results.xml +# The image stream measurement (docs/IMAGE_STREAMS.md), on a maintainer's dispatch only: figures in the log, no threshold. +if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch ]]; then + cmake --build build-jetson-webkitgtk --target image_stream_bench --parallel 2 + xvfb-run -a build-jetson-webkitgtk/test/web/image_stream_bench "$PWD/test/web/image-stream" \ + build-jetson-webkitgtk/image-streams-results.json + mkdir build-jetson-webkitgtk/image-stream-frames + test/web/image-stream/host-encoders.sh build-jetson-webkitgtk/test/web/image_stream_bench \ + "$PWD/build-jetson-webkitgtk/image-stream-frames" + rm -rf -- build-jetson-webkitgtk/image-stream-frames +fi ccache --show-stats diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index b124a5fa..553acb70 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -25,6 +25,10 @@ on: description: 'Also run the WebKitGTK aarch64 browser integration (GCC 13)' type: boolean default: false + image_streams: + description: 'Record the image stream measurement (docs/IMAGE_STREAMS.md) on WebView2 and WKWebView' + type: boolean + default: false repeat_desktop_tests: description: 'Also run the desktop matrix, repeating the complete CTest suite desktop_passes times' type: boolean @@ -354,6 +358,51 @@ jobs: build/diagnostics/ if-no-files-found: ignore + # The image stream measurement of the engines no maintainer machine has (#769, docs/IMAGE_STREAMS.md): on dispatch only, + # never on a push or a pull request, and no check of its figures. + image-stream-measurement: + if: github.event_name == 'workflow_dispatch' && inputs.image_streams + timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + platform: [windows-msvc-webview2, macos-clang-wkwebview] + include: + - platform: windows-msvc-webview2 + os: windows-2025 + options: -DWEBFRONT_EMBED_WEBVIEW2=ON -DWEBFRONT_WEBTEST_FRONTEND=WebView2 + - platform: macos-clang-wkwebview + os: macos-26 + options: -DWEBFRONT_EMBED_WKWEBVIEW=ON -DWEBFRONT_WEBTEST_FRONTEND=WKWebView + runs-on: ${{ matrix.os }} + steps: + - uses: actions/checkout@v7 + - uses: ./.github/actions/remove-node + - uses: ./.github/actions/setup-cmake + with: + version: '4.4.4' + - name: Initialize MSVC environment + if: runner.os == 'Windows' + uses: ilammy/msvc-dev-cmd@0b201ec74fa43914dc39ae48a89fd1d8cb592756 # v1 + - name: Setup Xcode + if: runner.os == 'macOS' + uses: maxim-lobanov/setup-xcode@ed7a3b1fda3918c0306d1b724322adc0b8cc0a90 # v1 + with: + xcode-version: latest + - name: Configure + run: >- + cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_EMBED_CEF=OFF -DWEBFRONT_ENABLE_TESTING=ON + -DWEBFRONT_BUILD_EXAMPLES=OFF -DWARNINGS_AS_ERRORS=OFF -DENABLE_CACHE=OFF -DCMAKE_CXX_SCAN_FOR_MODULES=OFF + ${{ matrix.options }} + - name: Measure + run: cmake --build build --target image_stream_report --parallel 4 + - name: Retain the report + uses: actions/upload-artifact@v4 + with: + name: image-streams-${{ matrix.platform }} + path: build/image-streams.json + if-no-files-found: error + desktop-native: if: github.event_name != 'workflow_dispatch' || inputs.repeat_desktop_tests permissions: diff --git a/docs/JETSON_RUNNER.md b/docs/JETSON_RUNNER.md index 3d540e7f..13226fb5 100644 --- a/docs/JETSON_RUNNER.md +++ b/docs/JETSON_RUNNER.md @@ -124,6 +124,8 @@ CTest limit. This scales the documented unit-test budget without skipping work. The job builds CEF-off with WebKitGTK disabled and runs the complete CTest suite, then builds WebKitGTK 6.0 and runs `web-integration` on the real Tegra stack. +A manual dispatch then runs the image stream measurement ([IMAGE_STREAMS](IMAGE_STREAMS.md)) with its host encoder +timings; its figures are the `IMAGE-STREAMS` and `ENCODER` lines of the job log. The scheduled run does not measure. CUDA is required (`WEBFRONT_HOST_LOOP_CUDA=ON`, Orin SM 87); its CPU/GPU image comparison is also run directly so a missing GPU produces exit 4 instead of a successful CTest skip. CEF remains optional and is covered by the separate hosted From b38bedabb9bff79df9041fc54c00a22b30462714 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:54:07 +0100 Subject: [PATCH 05/20] Select the image stream track and record the measurements (#769) --- docs/CHANGELOG.md | 3 +- docs/IMAGE_STREAMS.md | 165 ++++++++++++++++++++++++++++++++--------- docs/PROJECT_STATUS.md | 3 + 3 files changed, 135 insertions(+), 36 deletions(-) diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 62a3c049..83f3340c 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -27,7 +27,8 @@ these entries stays in the GitHub releases and the Git history. - Build an installer of your application with `webfront_package()`: Debian package with the WebKitGTK profile, macOS disk image or NSIS installer that detects the WebView2 runtime (#762, ADR-028, `docs/DISTRIBUTION.md`). - Replace an executable with a signed one, with rollback, using the optional `webfront/components/update/Updater.hpp` (#762, ADR-028, `docs/DISTRIBUTION.md`). - Write the SPDX bill of materials of your application with `webfront_write_sbom()`, with declared licenses, web engines and system libraries (#762, ADR-028, `docs/DISTRIBUTION.md`). -- First measurements of image streams to the page: raw frames, JPEG and WebCodecs availability under CEF and WebKitGTK (#769, `docs/IMAGE_STREAMS.md`). +- Show images of the host in the page with the `examples/image-stream/` example: JPEG frames skipped when the page lags, typed-array pixels as fallback (#769, `docs/IMAGE_STREAMS.md`). +- Compare the ways to send images to the page with the manual `image_stream_report` target: bridge, streamed route, shared memory prototype, WebCodecs and host encoders (#769, `docs/IMAGE_STREAMS.md`). - Open an embedded window maximized, full screen, without a frame or with a minimum size (`WindowOptions`), on WebKitGTK and CEF (#764, `docs/FRONTENDS.md`). - `wf dev` applies a change of the stylesheet alone without reloading the page, once an environment with it is published (#763, ADR-014). - Check your pages for accessibility in `wf test` with axe-core: a guide says how, and the forms generated from C++ and the fallback page are checked in CI (#768, `docs/ACCESSIBILITY.md`). diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index e2b06e83..8aa1c992 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -1,51 +1,146 @@ -# Sending images to the page: first measurements +# Sending images to the page -Measurements for #769, on one machine, of what the page side of an image stream costs. They are **not** a comparison of -complete pipelines: no encoding on the host was measured. +A host that produces images (a camera, a renderer, a CUDA computation) has several ways to put them on a canvas. This +page records the measurements of #769, the track selected from them and how to run both again. -## Configuration +## What to use -AMD Ryzen 9 3900X, Linux x86_64, under Xvfb (no GPU acceleration to rely on), Release build, 2026-12-05. CEF -(Chromium 156) and WebKitGTK 6.0 (2.52.6). Mean of 30 iterations after one warm-up. +**Send JPEG frames over the bridge, let the page ask for the next one only once it has drawn the previous one, and keep +typed-array pixels as the fallback.** The runnable example is `examples/image-stream/`: -The frame is synthetic (gradients, a checkerboard, three bits of noise in one channel). Its JPEG at quality 0.85 is -very small (17 KB for 960 x 720): a camera image is typically many times larger, so the JPEG figures are optimistic. +```bash +cmake --build build --target WebFrontImageStream --parallel 2 +build/examples/WebFrontImageStream # JPEG when the build found libjpeg +build/examples/WebFrontImageStream --raw # the typed-array fallback +``` -`echo` is a call of a C++ function that returns the bytes it received: the frame travels **both ways** and is copied on -the C++ side. A stream from the host pays one of the two ways. +- The page calls `image.next(after, jpeg)` and receives the newest image after `after`. What it has no time for is + skipped, so latency does not grow when the page or the network is slow. No `WebFront.js`, wire format or core change. +- JPEG is encoded with libjpeg, searched by default on Linux only (`-DWEBFRONT_IMAGE_STREAM_JPEG=ON` elsewhere, with a + libjpeg of your toolchain). Without it, or when the page cannot decode, the pixels are sent as they are. +- At 960 x 720 the fallback is usable on a desktop; at 1920 x 1080 and 30 images a second it costs a large part of the + frame period (see below). -## Results +The example asks for one image at a time. The benchmark keeps two in flight, so its throughput figures are higher than +the example's would be; its latencies at 30 images a second are the relevant comparison. -| | CEF 960x720 | CEF 1920x1080 | WebKitGTK 960x720 | WebKitGTK 1920x1080 | -| --- | --- | --- | --- | --- | -| Raw RGBA, bytes | 2.8 MB | 8.3 MB | 2.8 MB | 8.3 MB | -| JPEG, bytes | 17 KB | 41 KB | 17 KB | 41 KB | -| Raw echo | 24.8 ms | 75.8 ms | 32.8 ms | 90.4 ms | -| JPEG echo | 0.5 ms | 0.8 ms | 0.6 ms | 0.9 ms | -| Raw draw (`putImageData`) | 0.1 ms | 0.7 ms | 0.9 ms | 2.6 ms | -| JPEG decode and draw (`createImageBitmap`) | 2.0 ms | 6.2 ms | 14.9 ms | 35.1 ms | +## What was measured + +`image_stream_bench` (`test/web/ImageStreamBenchmark.cpp`) runs the same page in the engine of the browser tests. The +host holds 16 synthetic RGBA frames (gradients, a moving checkerboard, three bits of noise in every channel) and sends +them by one track; the page draws each frame, reads one pixel back, and acknowledges it. At most two frames are +unacknowledged. **Latency** is read on the host's clock from the start of a frame's preparation (JPEG encoding included) +to the reception of its acknowledgement, so it includes the way back of a small message. **CPU** is in cores: the host +process, and the engine's own processes (Linux and Windows). Each case runs 5 s after 1 s of warm-up, at 30 images a +second and as fast as the acknowledgements allow. + +| Track | Host to page | +| --- | --- | +| raw-bridge | RGBA as a typed array, one bridge call per frame | +| raw-route | RGBA in one long response of an `addRoute` route, read with `fetch` | +| jpeg-bridge | JPEG quality 0.85 (libjpeg), bridge call, `createImageBitmap` | +| jpeg-route | the same JPEG through the route | +| raw-shared | WebKitGTK only, prototype: POSIX shared memory read by a web process extension, one copy in the web process | + +Configuration: AMD Ryzen 9 3900X (24 threads), Ubuntu 26.04, GCC 16.1 Release, Xvfb (no GPU acceleration to rely on), +WebKitGTK 2.52.6 and CEF (Chromium 156), 2026-12-06, one run each. **The machine was not idle** (load average about 15 +from other builds): compare the tracks of one table, and read small differences as noise. + +### WebKitGTK + +Latency is the median / 95th percentile in milliseconds; CPU is host + engine. + +| Track | 960x720 at 30 fps: latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | +| --- | --- | ---: | --- | ---: | +| raw-bridge | 15.6 / 18.5, 0.68 + 0.58 | 97 | 29.9, 50.8 / 54.5, 0.81 + 1.41 | 40 | +| raw-route | 17.3 / 39.1, 1.01 + 1.53 | 59 | 21.3, 65.8 / 110, 1.29 + 3.05 | 22 | +| jpeg-bridge | 8.1 / 10.5, 0.72 + 0.31 | 190 | 30.1, 17.3 / 20.5, 0.82 + 0.49 | 75 | +| jpeg-route | 40.7 / 44.0, 0.64 + 0.31 | stalled | 30.1, 49.3 / 52.5, 0.82 + 0.53 | 55 | +| raw-shared | 2.9 / 4.8, 0.70 + 0.15 | 443 | 30.1, 6.0 / 8.6, 0.69 + 0.22 | 145 | + +### CEF + +| Track | 960x720 at 30 fps: latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | +| --- | --- | ---: | --- | ---: | +| raw-bridge | 8.1 / 11.3, 0.06 + 0.31 | 123 | 29.9, 21.6 / 26.1, 0.13 + 0.83 | 42 | +| raw-route | 12.0 / 18.7, 0.33 + 0.73 | 89 | 26.7, 53.9 / 80.2, 0.98 + 1.97 | 23 | +| jpeg-bridge | 5.5 / 6.7, 0.09 + 0.13 | 286 | 30.1, 18.7 / 23.9, 0.23 + 0.37 | 87 | +| jpeg-route | 6.0 / 7.1, 0.09 + 0.14 | 265 | 30.1, 18.5 / 22.9, 0.27 + 0.40 | 92 | + +The WebKitGTK host figures are higher than the CEF ones for the same host work; the cause was not looked for. -`VideoDecoder.isConfigSupported` answered: +A JPEG frame is about 81 KB at 960 x 720 and 238 KB at 1920 x 1080 (raw: 2.8 MB and 8.3 MB). libjpeg took about 2 ms +and 6 ms per frame; drawing it took the page 3 to 5 ms and 10 to 12 ms. -| Codec | CEF | WebKitGTK | +### Encoding on the host + +`test/web/image-stream/host-encoders.sh` times ffmpeg 8.0.1 on the same frames (160 per size, RGBA input, conversion +included), wall / CPU milliseconds per frame and bytes per frame: + +| Encoder | 960x720 | 1920x1080 | | --- | --- | --- | -| VP8 | yes | yes | -| VP9 | yes | yes | -| H.264 baseline | **no** | yes | +| mjpeg `-q:v 4` | 2.1 / 8.5, 32 KB | 4.1 / 25, 93 KB | +| libx264 ultrafast zerolatency | 2.7 / 12, 8 KB | 6.6 / 37, 16 KB | +| libvpx (VP8) realtime | 26 / 256, 17 KB | 36 / 368, 26 KB | +| libvpx-vp9 realtime | 13 / 44, 16 KB | 23 / 107, 18 KB | +| h264_vaapi (AMD GPU) | 1.9 / 6.7, 4 KB | 4.0 / 18, 8 KB | +| h264_nvenc, h264_v4l2m2m | unavailable on this machine | unavailable | + +The encoders were not tuned to one quality, so sizes are not a comparison of compression. **NVENC was not measured**: this +machine has no NVIDIA GPU, and NVIDIA lists the Jetson Orin Nano without a hardware video encoder. -## What can be concluded +### Decoding with WebCodecs -- Raw frames are dominated by the transport at these sizes; a compressed frame moves that cost to encoding and decoding. -- Where JPEG pays off depends on the engine: decoding costs several times more under WebKitGTK than under CEF here, and - at 1920 x 1080 it alone exceeds a 30 images per second budget there. -- WebCodecs exists in both engines, but an H.264 stream cannot be assumed: the CEF build used here does not decode it. +The page encodes 90 frames with the engine's `VideoEncoder`, then times each from `decode()` to the drawn output, one at a +time (median / 95th percentile). The content differs from the frames above. + +| Codec | WebKitGTK 960x720 | WebKitGTK 1920x1080 | CEF 960x720 | CEF 1920x1080 | +| --- | --- | --- | --- | --- | +| VP8 | 5 / 7 ms | 10 / 14 ms | 4.2 / 5.4 ms | 10.3 / 13.2 ms | +| VP9 | 5 / 7 ms | 11 / 14 ms | 5.0 / 6.8 ms | 10.8 / 13.7 ms | +| H.264 baseline (Annex B) | `EncodingError: Decode error` | same | decoding not supported | decoding not supported | -No transport is selected. Still to measure: host-side encoding (software and NVENC), actual WebCodecs decoding latency, -shared memory, back-pressure under load, CPU load, WebView2, WKWebView and a Jetson Orin Nano. +## Why the other tracks were not selected + +- **WebCodecs.** Decoding a frame costs about what decoding a JPEG does. What it saves is bandwidth, which the loopback + does not lack. It needs a video encoder in the host: the software VP8 and VP9 timings above are close to or beyond the + frame period at 1920 x 1080, and H.264, the codec with fast and hardware encoders, did not decode in either engine + tested (WebKitGTK accepts the configuration and then fails on the stream its own encoder produced; whether another + H.264 stream decodes was not tried). Reconsider it for a remote browser on a narrow link. +- **Streamed route.** In WebKitGTK, at 30 images a second, a frame arrived about one frame period later than over the + bridge, as if the end of each frame were held until more data came, and the unpaced 960 x 720 JPEG case stalled. CEF + showed no such delay, which points to the WebKit side of the exchange; the cause was not identified. Raw frames were + slower than over the bridge in both engines (the server sends a route's body in chunks of 8 KiB, each read on a worker + thread, which may explain it). One viewer also holds one of the 4 route worker threads for as long as it watches + ([HTTP_ASSETS](HTTP_ASSETS.md#streaming-and-dynamic-routes-454)). +- **Shared memory.** By far the fastest, and the only track that holds 1920 x 1080 raw frames comfortably. It is not + selected: it was prototyped for one embedded engine only, needs a native web process extension in the page's process, + needs WebKitGTK's sandbox disabled (the development mode), offers nothing to a browser on another machine, and the + prototype filters neither origin nor frame as [ADR-017](adr/ADR-017-acces-direct-aux-frontends.md) requires. ADR-017 is + therefore unchanged. A zero-copy variant was tried and **fails**: giving the page an `ArrayBuffer` over the mapping + (`jsc_value_new_array_buffer`) kills the web process with `Disabling Primitive gigacage is forbidden`. + WebView2's shared buffers (measured at small sizes in ADR-017) were not tried with images; WKWebView has no public + shared memory API; CEF was not prototyped. + +## Not measured + +- WebView2 and WKWebView: no maintainer machine used here runs them. The `image_streams` dispatch of `BuildAndTest.yml` + records them on hosted runners (artifacts `image-streams-*`); their host has no JPEG library, so the page encodes the + JPEG tracks and there is no host encoding figure. On macOS the engine's CPU is not measured. **No figures are recorded + here yet.** +- Jetson Orin Nano: measured by a manual dispatch of the hardware validation ([JETSON_RUNNER](JETSON_RUNNER.md)). **No + figures are recorded here yet.** +- A GPU-accelerated display, a physical screen, a browser on another machine. ## Running it again -`test/web/suite/bench/image-streams.mjs` is not part of the suite. Add `import '../bench/image-streams.mjs';` at the end -of `test/web/suite/specs/webfront-specs.mjs`, run the browser integration test with `ctest -V` and read the -`IMAGE-STREAMS` line. Keep the rest of the suite: the test program also requires what the regular specs report. The -suite then runs longer; raise its `--timeout` if it stops before the report. +```bash +cmake -S . -B build-bench -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_ENABLE_TESTING=ON -DWEBFRONT_EMBED_CEF=OFF \ + -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK +cmake --build build-bench --target image_stream_report --parallel # under xvfb-run without a display +test/web/image-stream/host-encoders.sh build-bench/test/web/image_stream_bench "$(mktemp -d)" +``` + +The report is `build-bench/image-streams.json`. For CEF, configure with `-DWEBFRONT_EMBED_CEF=ON` instead of the two +WebKitGTK options. The benchmark is never part of the default build or of CTest; the example is checked in a real +engine by the `ImageStreamExample-jpeg` and `ImageStreamExample-raw` cases. diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 9e68f166..d90f278a 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -30,6 +30,9 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer A second native window of the same application (`app.openSecondaryWindow()`, #616) exists on WebKitGTK, WKWebView and WebView2; CEF and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. +- **Images from the host.** [The image stream example](IMAGE_STREAMS.md) sends JPEG frames (libjpeg, searched on Linux by + default) or typed-array pixels over the bridge; it is checked in the browser tests' engine. WebView2, WKWebView and + Jetson figures are not recorded yet. - **Application spaces.** One process serves several independent users, each under `prefix//` with its own functions, page handlers, broadcasts and routes (`app.spaces()`, `WebFront::Space`, #671); the application owns the spaces and ends them. A space isolates dispatch, not users of one process from each other. See [spaces](SPACES.md). From bd4fe4195a2c2fb0d4101a0a830c4ed8afc470a7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 01:58:46 +0100 Subject: [PATCH 06/20] Use the source header's thread and allocation values (#769) --- examples/image-stream/ImageStream.cpp | 2 +- examples/image-stream/ImageStreamHost.hpp | 2 +- test/web/ImageStreamBenchmark.cpp | 2 +- test/web/ImageStreamWebExtension.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/examples/image-stream/ImageStream.cpp b/examples/image-stream/ImageStream.cpp index 309b4385..d3951e97 100644 --- a/examples/image-stream/ImageStream.cpp +++ b/examples/image-stream/ImageStream.cpp @@ -4,7 +4,7 @@ // // WebFront — examples // Role: Shows a stream of images of the host in the page: JPEG frames, or pixels with --raw or without a JPEG library. -// Thread: multi-thread | Alloc: unrestricted +// Thread: thread-safe | Alloc: unrestricted // LLM: example; see ImageStreamHost.hpp and docs/IMAGE_STREAMS.md #include "../PortOption.hpp" diff --git a/examples/image-stream/ImageStreamHost.hpp b/examples/image-stream/ImageStreamHost.hpp index f714f3c6..bde84c42 100644 --- a/examples/image-stream/ImageStreamHost.hpp +++ b/examples/image-stream/ImageStreamHost.hpp @@ -4,7 +4,7 @@ // // WebFront — examples // Role: A source of images and the callbacks and page that show them: JPEG frames, or pixels in a typed array. -// Thread: multi-thread | Alloc: unrestricted +// Thread: thread-safe | Alloc: unrestricted // LLM: example; the source must outlive the application that registers its callbacks #pragma once diff --git a/test/web/ImageStreamBenchmark.cpp b/test/web/ImageStreamBenchmark.cpp index b7e7cefe..ec77c08d 100644 --- a/test/web/ImageStreamBenchmark.cpp +++ b/test/web/ImageStreamBenchmark.cpp @@ -4,7 +4,7 @@ // // WebFront — tests/web // Role: End-to-end measurement of the ways to send images from the host to the page (#769). -// Thread: multi-thread | Alloc: unrestricted +// Thread: thread-safe | Alloc: unrestricted // LLM: manual benchmark; fails on a wrong run, never on a timing // The host produces RGBA frames, sends them by one of several tracks, and the page draws each one and acknowledges it: diff --git a/test/web/ImageStreamWebExtension.cpp b/test/web/ImageStreamWebExtension.cpp index 43da8c02..d06dbdea 100644 --- a/test/web/ImageStreamWebExtension.cpp +++ b/test/web/ImageStreamWebExtension.cpp @@ -4,7 +4,7 @@ // // WebFront — tests/web // Role: Prototype WebKitGTK web process extension exposing a host's shared memory to the page (#769). -// Thread: ui-loop | Alloc: bounded +// Thread: ui-loop | Alloc: unrestricted // LLM: measurement prototype only; no origin or frame filtering, never ship it as is // Loaded by image_stream_bench into the web process: window.wfSharedSlot(slot, length) returns the first bytes of a From 3c5fd2a2d5beb19804d8c1c9c8c97c914cafbceb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 02:30:35 +0100 Subject: [PATCH 07/20] Record the WebView2 and WKWebView image stream measurements (#769) --- docs/IMAGE_STREAMS.md | 75 +++++++++++++++++++++++++++++++----------- docs/PROJECT_STATUS.md | 4 +-- 2 files changed, 58 insertions(+), 21 deletions(-) diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index 8aa1c992..c9040127 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -18,8 +18,9 @@ build/examples/WebFrontImageStream --raw # the typed-array fallback skipped, so latency does not grow when the page or the network is slow. No `WebFront.js`, wire format or core change. - JPEG is encoded with libjpeg, searched by default on Linux only (`-DWEBFRONT_IMAGE_STREAM_JPEG=ON` elsewhere, with a libjpeg of your toolchain). Without it, or when the page cannot decode, the pixels are sent as they are. -- At 960 x 720 the fallback is usable on a desktop; at 1920 x 1080 and 30 images a second it costs a large part of the - frame period (see below). +- Which format is faster depends on the engine and the machine. Under WebKitGTK, CEF and WebView2, JPEG had the lower + latency; on the hosted macOS runner, where WKWebView decoded a JPEG slowly, raw pixels did as well at 960 x 720 and + better at 1920 x 1080 (see below). Measure on your target; `--raw` is one option away. The example asks for one image at a time. The benchmark keeps two in flight, so its throughput figures are higher than the example's would be; its latencies at 30 images a second are the relevant comparison. @@ -72,6 +73,40 @@ The WebKitGTK host figures are higher than the CEF ones for the same host work; A JPEG frame is about 81 KB at 960 x 720 and 238 KB at 1920 x 1080 (raw: 2.8 MB and 8.3 MB). libjpeg took about 2 ms and 6 ms per frame; drawing it took the page 3 to 5 ms and 10 to 12 ms. +### WebView2 and WKWebView (hosted runners) + +Recorded on 2026-12-06 by the `image_streams` dispatch of `BuildAndTest.yml`, Release builds, one run each, on GitHub's +hosted virtual machines: `windows-2025` (4 logical processors reported to the page, Edge WebView2 158) and `macos-26` +(3 reported, system WKWebView). Their GPU and the load of their physical hosts are unknown, so **do not compare these +figures with the tables above**. Neither host had a JPEG library: the page encoded the JPEG frames once, beforehand, so +**the latencies contain no encoding time** and are not comparable with the JPEG latencies above either. There is no +shared memory track, and on macOS the engine's CPU is not measured. + +| Track, WebView2 | 960x720 at 30 fps: latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | +| --- | --- | ---: | --- | ---: | +| raw-bridge | 4.5 / 10.2, 0.02 + 0.21 | 218 | 30.0, 11.9 / 14.2, 0.07 + 0.49 | 76 | +| raw-route | 10.5 / 12.1, 0.32 + 0.57 | 98 | 30.0, 31.9 / 36.6, 1.08 + 1.61 | 32 | +| jpeg-bridge | 3.3 / 3.7, 0.02 + 0.13 | 405 | 30.0, 7.3 / 7.8, 0.02 + 0.26 | 147 | +| jpeg-route | 3.3 / 3.6, 0.02 + 0.15 | 396 | 30.0, 7.5 / 8.1, 0.04 + 0.29 | 149 | + +| Track, WKWebView | 960x720 at 30 fps: fps, latency, host CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, host CPU | 1920x1080 max fps | +| --- | --- | ---: | --- | ---: | +| raw-bridge | 28.0, 17.0 / 31.0, 0.09 | 110 | 28.2, 24.6 / 41.0, 0.13 | 50 | +| raw-route | 25.4, 32.8 / 105, 0.45 | 32 | 12.6, 158 / 176, 0.60 | 10 | +| jpeg-bridge | 28.4, 18.1 / 42.2, 0.04 | 52 | 29.4, 34.6 / 72.3, 0.04 | 30 | +| jpeg-route | 17.2, 47.7 / 169, 0.04 | stalled | 24.6, 67.3 / 84.3, 0.10 | 31 | + +The JPEG frames each engine encoded at "quality 0.85" differ in size: 53 KB and 153 KB under WebView2, 155 KB and 461 KB +under WKWebView. Drawing one took 2.5 ms and 6.5 ms under WebView2, 16 ms and 31 ms under WKWebView. + +WebCodecs, same method as below (median / 95th percentile): + +| Codec | WebView2 960x720 | WebView2 1920x1080 | WKWebView 960x720 | WKWebView 1920x1080 | +| --- | --- | --- | --- | --- | +| VP8 | 2.9 / 3.3 ms | 7.7 / 8.7 ms | 41 / 70 ms | 46 / 77 ms | +| VP9 | 2.7 / 3.2 ms | 7.3 / 8.3 ms | 27 / 53 ms | 39 / 51 ms | +| H.264 baseline (Annex B) | 2.3 / 2.8 ms | 6.3 / 7.3 ms | 29 / 39 ms | 37 / 51 ms | + ### Encoding on the host `test/web/image-stream/host-encoders.sh` times ffmpeg 8.0.1 on the same frames (160 per size, RGBA input, conversion @@ -102,17 +137,20 @@ time (median / 95th percentile). The content differs from the frames above. ## Why the other tracks were not selected -- **WebCodecs.** Decoding a frame costs about what decoding a JPEG does. What it saves is bandwidth, which the loopback - does not lack. It needs a video encoder in the host: the software VP8 and VP9 timings above are close to or beyond the - frame period at 1920 x 1080, and H.264, the codec with fast and hardware encoders, did not decode in either engine - tested (WebKitGTK accepts the configuration and then fails on the stream its own encoder produced; whether another - H.264 stream decodes was not tried). Reconsider it for a remote browser on a narrow link. -- **Streamed route.** In WebKitGTK, at 30 images a second, a frame arrived about one frame period later than over the - bridge, as if the end of each frame were held until more data came, and the unpaced 960 x 720 JPEG case stalled. CEF - showed no such delay, which points to the WebKit side of the exchange; the cause was not identified. Raw frames were - slower than over the bridge in both engines (the server sends a route's body in chunks of 8 KiB, each read on a worker - thread, which may explain it). One viewer also holds one of the 4 route worker threads for as long as it watches - ([HTTP_ASSETS](HTTP_ASSETS.md#streaming-and-dynamic-routes-454)). +- **WebCodecs.** Decoding a frame costs about what decoding a JPEG does, or more (WKWebView on the hosted runner). What + it saves is bandwidth, which the loopback does not lack. It needs a video encoder in the host: the software VP8 and + VP9 timings above are close to or beyond the frame period at 1920 x 1080, and H.264, the codec with fast and hardware + encoders, decodes under WebView2 and WKWebView but not under WebKitGTK (which accepts the configuration and then + fails on the stream its own encoder produced; whether another H.264 stream decodes was not tried) nor the CEF build. + Reconsider it for a remote browser on a narrow link. +- **Streamed route.** It depends on the engine. Under WebView2 and CEF its JPEG figures equal the bridge's. Under + WKWebView it fell behind (17 and 25 images a second where 30 were asked, and the same stall of the unpaced 960 x 720 + JPEG case as under WebKitGTK). In WebKitGTK, at 30 images a second, a frame arrived about one frame period later than + over the bridge, as if the end of each frame were held until more data came, and the unpaced 960 x 720 JPEG case + stalled. Both WebKit engines being affected points to WebKit's side of the exchange; the cause was not identified. + Raw frames were slower than over the bridge in all four engines (the server sends a route's body in chunks of 8 KiB, + each read on a worker thread, which may explain it). One viewer also holds one of the 4 route worker threads for as + long as it watches ([HTTP_ASSETS](HTTP_ASSETS.md#streaming-and-dynamic-routes-454)). - **Shared memory.** By far the fastest, and the only track that holds 1920 x 1080 raw frames comfortably. It is not selected: it was prototyped for one embedded engine only, needs a native web process extension in the page's process, needs WebKitGTK's sandbox disabled (the development mode), offers nothing to a browser on another machine, and the @@ -124,12 +162,11 @@ time (median / 95th percentile). The content differs from the frames above. ## Not measured -- WebView2 and WKWebView: no maintainer machine used here runs them. The `image_streams` dispatch of `BuildAndTest.yml` - records them on hosted runners (artifacts `image-streams-*`); their host has no JPEG library, so the page encodes the - JPEG tracks and there is no host encoding figure. On macOS the engine's CPU is not measured. **No figures are recorded - here yet.** -- Jetson Orin Nano: measured by a manual dispatch of the hardware validation ([JETSON_RUNNER](JETSON_RUNNER.md)). **No - figures are recorded here yet.** +- **Jetson Orin Nano: no figures.** The measurement is part of the manual hardware validation + ([JETSON_RUNNER](JETSON_RUNNER.md)), but its job was skipped when dispatched: its guard still requires the repository + name `ambroise-leclerc/WebFront`, which no longer matches since the move to BareNative. Changing that guard is a + maintainer's decision. +- Host-side JPEG encoding on Windows and macOS, and the engine's CPU on macOS. - A GPU-accelerated display, a physical screen, a browser on another machine. ## Running it again diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index d90f278a..03fc638b 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -31,8 +31,8 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. - **Images from the host.** [The image stream example](IMAGE_STREAMS.md) sends JPEG frames (libjpeg, searched on Linux by - default) or typed-array pixels over the bridge; it is checked in the browser tests' engine. WebView2, WKWebView and - Jetson figures are not recorded yet. + default) or typed-array pixels over the bridge; it is checked in the browser tests' engine. No Jetson figures: the + hardware job's repository guard skips it since the repository moved. - **Application spaces.** One process serves several independent users, each under `prefix//` with its own functions, page handlers, broadcasts and routes (`app.spaces()`, `WebFront::Space`, #671); the application owns the spaces and ends them. A space isolates dispatch, not users of one process from each other. See [spaces](SPACES.md). From cf32c30b60e676724809a9c30ee3449ab930167e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:07:41 +0100 Subject: [PATCH 08/20] Give the Jetson encoder frames a new directory removed on exit (#769) --- .github/scripts/jetson-orin.sh | 8 ++++---- test/web/image-stream/host-encoders.sh | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/.github/scripts/jetson-orin.sh b/.github/scripts/jetson-orin.sh index 6f5a7ec1..3e635132 100755 --- a/.github/scripts/jetson-orin.sh +++ b/.github/scripts/jetson-orin.sh @@ -55,9 +55,9 @@ if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch ]]; then cmake --build build-jetson-webkitgtk --target image_stream_bench --parallel 2 xvfb-run -a build-jetson-webkitgtk/test/web/image_stream_bench "$PWD/test/web/image-stream" \ build-jetson-webkitgtk/image-streams-results.json - mkdir build-jetson-webkitgtk/image-stream-frames - test/web/image-stream/host-encoders.sh build-jetson-webkitgtk/test/web/image_stream_bench \ - "$PWD/build-jetson-webkitgtk/image-stream-frames" - rm -rf -- build-jetson-webkitgtk/image-stream-frames + # A new directory each time, removed however the script ends. The trap is set only once mktemp has named it. + frames=$(mktemp -d "$PWD/build-jetson-webkitgtk/image-stream-frames.XXXXXX") + trap 'rm -rf -- "${frames:?}"' EXIT + test/web/image-stream/host-encoders.sh build-jetson-webkitgtk/test/web/image_stream_bench "$frames" fi ccache --show-stats diff --git a/test/web/image-stream/host-encoders.sh b/test/web/image-stream/host-encoders.sh index 2bb9e2a0..427d8ce6 100644 --- a/test/web/image-stream/host-encoders.sh +++ b/test/web/image-stream/host-encoders.sh @@ -11,7 +11,7 @@ if command -v gst-inspect-1.0 >/dev/null; then fi command -v ffmpeg >/dev/null || { echo "ENCODER ffmpeg: unavailable (not installed)"; exit 0; } "$bench" --dump-frames "$work" -ffmpeg -version | head -1 +ffmpeg -version | sed -n 1p # reads it all: head would break the pipe under pipefail for size in 960x720 1920x1080; do for encoder in "mjpeg -q:v 4" "libx264 -preset ultrafast -tune zerolatency" "libvpx -deadline realtime -cpu-used 8 -b:v 4M" \ "libvpx-vp9 -deadline realtime -cpu-used 8 -row-mt 1 -b:v 4M" "h264_nvenc -preset p1 -tune ull" "h264_v4l2m2m" \ From 38854b62a6a82387fdbaaa573b5ab5031d40de2e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:07:41 +0100 Subject: [PATCH 09/20] Fail the image stream benchmark when its report or a case is lost (#769) --- test/unit/CMakeLists.txt | 2 +- test/unit/ImageStreamReportTests.cpp | 43 ++++++++++++++++++++++++++++ test/web/ImageStreamBenchmark.cpp | 43 +++++++++++++++++++++------- test/web/ImageStreamReport.hpp | 28 ++++++++++++++++++ test/web/image-stream/bench.js | 1 + 5 files changed, 105 insertions(+), 12 deletions(-) create mode 100644 test/unit/ImageStreamReportTests.cpp create mode 100644 test/web/ImageStreamReport.hpp diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index fe4e3a08..9a171241 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -79,7 +79,7 @@ list(APPEND TESTS_LIST TlsTests.cpp) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp HTTPKeepAliveTests.cpp HTTPRangeTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp BridgeContainersTests.cpp BridgeStructsTests.cpp BridgeBindingsTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) -list(APPEND TESTS_LIST DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) +list(APPEND TESTS_LIST ImageStreamReportTests.cpp DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp WatchTreeTests.cpp WatchContainersTests.cpp WatchPassTests.cpp WatchWriteTests.cpp IntrospectionTests.cpp BridgeStateTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp AutomationStateTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp BridgeLightTests.cpp BridgeLightPage.cpp) list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp WindowControlTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) diff --git a/test/unit/ImageStreamReportTests.cpp b/test/unit/ImageStreamReportTests.cpp new file mode 100644 index 00000000..41672d40 --- /dev/null +++ b/test/unit/ImageStreamReportTests.cpp @@ -0,0 +1,43 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/unit +// Role: The report of image_stream_bench: written whole, or an error. +// Thread: worker-safe | Alloc: heap-init +// LLM: small file tests + +#include "../web/ImageStreamReport.hpp" +#include + +#include +#include +#include +#include + +using namespace webfront::bdd; + +const Scenario imageStreamReport{"The image stream benchmark report is written or fails", [] { + const auto directory = std::filesystem::temp_directory_path() / "webfront-image-stream-report"; + std::filesystem::remove_all(directory); + std::filesystem::create_directories(directory); + then("a writable path holds the report and a line end", [&] { + image_stream_bench::writeReport(directory / "report.json", "{}"); + std::ifstream input(directory / "report.json", std::ios::binary); + const std::string text{std::istreambuf_iterator(input), {}}; + requireEqual(text, std::string("{}\n")); + }); + then("a path that cannot be opened is an error", [&] { + requireThrows([&] { + image_stream_bench::writeReport(directory / "missing" / "report.json", "{}"); + }); + }); +#ifdef __linux__ + then("a device without room is an error", [&] { + requireThrows([&] { + image_stream_bench::writeReport("/dev/full", "{}"); + }); + }); +#endif + std::filesystem::remove_all(directory); + }}; diff --git a/test/web/ImageStreamBenchmark.cpp b/test/web/ImageStreamBenchmark.cpp index ec77c08d..c860f15b 100644 --- a/test/web/ImageStreamBenchmark.cpp +++ b/test/web/ImageStreamBenchmark.cpp @@ -14,6 +14,7 @@ // image_stream_bench [] [--seconds N] // image_stream_bench --dump-frames (the frames, for image-stream/host-encoders.sh) +#include "ImageStreamReport.hpp" #include #include @@ -239,12 +240,16 @@ struct SharedFrames { SharedFrames() { const int fd = shm_open(name.c_str(), O_CREAT | O_EXCL | O_RDWR, 0600); - if (fd < 0 || ftruncate(fd, static_cast(slotSize * sharedSlots)) != 0) + if (fd < 0) throw std::runtime_error("cannot create the shared memory object"); - auto* mapped = mmap(nullptr, slotSize * sharedSlots, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); + void* mapped = MAP_FAILED; + if (ftruncate(fd, static_cast(slotSize * sharedSlots)) == 0) + mapped = mmap(nullptr, slotSize * sharedSlots, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); - if (mapped == MAP_FAILED) + if (mapped == MAP_FAILED) { + shm_unlink(name.c_str()); // the destructor does not run throw std::runtime_error("cannot map the shared memory object"); + } data = static_cast(mapped); } SharedFrames(const SharedFrames&) = delete; @@ -265,6 +270,7 @@ struct Run { std::mutex mutex; std::condition_variable changed; bool stopping = false; + std::string producerError; // set: the case reports it instead of figures std::vector> pool, encoded; // raw frames; their JPEG when the page supplied it std::map inFlight; std::deque>> mailbox; // the route's next frames, each with its header @@ -409,6 +415,8 @@ class Bench { ui.jsFunction("bench.frame")(sequence, payload); } catch (const std::exception& error) { std::cerr << "image stream bench: " << error.what() << '\n'; + std::scoped_lock lock(state->mutex); + state->producerError = error.what(); return; } } @@ -454,7 +462,7 @@ class Bench { public: webfront::http::RouteTable::Registration route; - bool reported = false; + std::string failure = "the benchmark page closed without a report"; // empty: reported Bench(App& application, int duration, std::filesystem::path path) : app(application), seconds(duration), reportPath(std::move(path)) { route = app.addRoute("/frames/", [this](const webfront::http::RouteRequest&) { @@ -543,13 +551,25 @@ class Bench { + "}"; } stopProducer(); + // Read once the producer is joined: the figures of a case that stopped sending would mislead. + if (!state->producerError.empty()) + throw std::runtime_error("the host stopped sending: " + state->producerError); co_return json; }); app.cppFunction("benchReport", [this](const std::string& json) { - reported = true; std::cout << "IMAGE-STREAMS " << json << std::endl; - if (!reportPath.empty()) - std::ofstream(reportPath, std::ios::binary) << json << '\n'; + try { + if (!reportPath.empty()) + image_stream_bench::writeReport(reportPath, json); + failure.clear(); + } catch (const std::exception& error) { + failure = error.what(); + } + app.requestClose(); + }); + // A page that cannot go on says so, instead of leaving its window open for ever. + app.cppFunction("benchFailed", [this](const std::string& message) { + failure = "the benchmark page failed: " + message; app.requestClose(); }); } @@ -572,6 +592,7 @@ void dumpFrames(const std::filesystem::path& directory) { const auto frame = makeFrame(width, height, i); output.write(reinterpret_cast(frame.data()), static_cast(frame.size())); } + output.close(); if (!output) throw std::runtime_error("cannot write the frames"); } @@ -604,15 +625,15 @@ int main(int argc, char** argv) { setenv("WEBFRONT_BENCH_SHM_NAME", shared.name.c_str(), 1); setenv("WEBFRONT_BENCH_SHM_SIZE", std::to_string(SharedFrames::slotSize).c_str(), 1); #endif - bool reported = false; + std::string failure; { App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::absolute(positional[0])}); Bench bench(app, seconds, positional.size() > 1 ? positional[1] : ""); app.show("bench.html"); - reported = bench.reported; + failure = bench.failure; } - if (!reported) - throw std::runtime_error("the benchmark page closed without a report"); + if (!failure.empty()) + throw std::runtime_error(failure); return 0; } catch (const std::exception& error) { std::cerr << error.what() << '\n'; diff --git a/test/web/ImageStreamReport.hpp b/test/web/ImageStreamReport.hpp new file mode 100644 index 00000000..4b92074b --- /dev/null +++ b/test/web/ImageStreamReport.hpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/web +// Role: Writes the report file of image_stream_bench, or says that it could not. +// Thread: worker-safe | Alloc: unrestricted +// LLM: benchmark support; a lost report must end the benchmark with a failure + +#pragma once + +#include +#include +#include +#include + +namespace image_stream_bench { + +/// Writes `json` and a line end to `path`; throws std::runtime_error unless all of it reached the file. +inline void writeReport(const std::filesystem::path& path, std::string_view json) { + std::ofstream output(path, std::ios::binary); + output << json << '\n'; + output.close(); // a full disk may only show when the buffer is written + if (!output) + throw std::runtime_error("cannot write the report " + path.string()); +} + +} // namespace image_stream_bench diff --git a/test/web/image-stream/bench.js b/test/web/image-stream/bench.js index 1d83eb03..28031e96 100644 --- a/test/web/image-stream/bench.js +++ b/test/web/image-stream/bench.js @@ -172,4 +172,5 @@ })().catch(error => { console.error(error); document.getElementById('status').textContent = String(error); + webFront.cppFunction('benchFailed')(String(error)).catch(failure => console.error(failure)); }); From fec73b782c68bb795867d91099fbd1e1d45b6061 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:09:56 +0100 Subject: [PATCH 10/20] Time each decoded frame against the chunk of the same timestamp (#769) --- docs/IMAGE_STREAMS.md | 9 +++++++-- test/web/image-stream/bench.js | 28 ++++++++++++++++++++-------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index c9040127..8d663f07 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -126,8 +126,13 @@ machine has no NVIDIA GPU, and NVIDIA lists the Jetson Orin Nano without a hardw ### Decoding with WebCodecs -The page encodes 90 frames with the engine's `VideoEncoder`, then times each from `decode()` to the drawn output, one at a -time (median / 95th percentile). The content differs from the frames above. +The page encodes 90 frames with the engine's `VideoEncoder`, then times each from `decode()` to the drawn output of the +same timestamp, one at a time (median / 95th percentile); a frame not given within 250 ms is counted as held back and not +timed. The content differs from the frames above. + +The figures here and for WebView2 and WKWebView were recorded before the page matched outputs by timestamp. They are not +affected: a wrong match needed a held-back frame first, and every codec that decoded gave all 90 outputs in time, with +none held back. | Codec | WebKitGTK 960x720 | WebKitGTK 1920x1080 | CEF 960x720 | CEF 1920x1080 | | --- | --- | --- | --- | --- | diff --git a/test/web/image-stream/bench.js b/test/web/image-stream/bench.js index 28031e96..d2947497 100644 --- a/test/web/image-stream/bench.js +++ b/test/web/image-stream/bench.js @@ -84,7 +84,8 @@ return result; } - /** Encodes frames with the engine's encoder, then times each frame from decode() to its output, one at a time. */ + /** Encodes frames with the engine's encoder, then times each chunk from decode() to the output of the same timestamp, + * one at a time. */ async function measureCodec(codec, [w, h]) { if (typeof VideoDecoder === 'undefined' || typeof VideoEncoder === 'undefined') return {error: `no ${typeof VideoDecoder === 'undefined' ? 'VideoDecoder' : 'VideoEncoder'}`}; @@ -112,10 +113,16 @@ await encoder.flush(); encoder.close(); if (broken) throw broken; - let ready = null; + // The chunk being timed. A decoder that holds frames back may give an earlier one now: it does not end the wait. + let awaited = null; const decoder = new VideoDecoder({ - output: frame => { context.drawImage(frame, 0, 0); frame.close(); ready?.(); }, - error: error => { broken = error; ready?.(); } + output: frame => { + const {timestamp} = frame; + context.drawImage(frame, 0, 0); + frame.close(); + if (awaited?.timestamp === timestamp) awaited.resolve(true); + }, + error: error => { broken = error; awaited?.resolve(false); } }); decoder.configure({codec, codedWidth: w, codedHeight: h, optimizeForLatency: true}); canvas.width = w; @@ -123,14 +130,19 @@ const times = []; let late = 0, bytes = 0; for (const chunk of chunks) { + const output = new Promise(resolve => { awaited = {timestamp: chunk.timestamp, resolve}; }); const start = performance.now(); - const output = new Promise(resolve => { ready = () => resolve(true); }); decoder.decode(chunk); - // A decoder that holds frames back gives nothing until it has more input: count it instead of waiting. - if (await Promise.race([output, new Promise(resolve => setTimeout(() => resolve(false), 250))])) { + // A decoder that holds frames back gives nothing until it has more input: count it instead of waiting. Its + // output, when it comes, is not timed: the delay would be that of this loop. + let timer; + const given = await Promise.race([output, new Promise(resolve => { timer = setTimeout(() => resolve(false), 250); })]); + clearTimeout(timer); + awaited = null; + if (given) { context.getImageData(0, 0, 1, 1); times.push(performance.now() - start); - } else + } else if (!broken) ++late; bytes += chunk.byteLength; if (broken) throw broken; From e025c4b00fa8c0bc823e627a1c39c96af15af102 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:14:22 +0100 Subject: [PATCH 11/20] Make the host encoder timing script executable (#769) --- test/web/image-stream/host-encoders.sh | 0 1 file changed, 0 insertions(+), 0 deletions(-) mode change 100644 => 100755 test/web/image-stream/host-encoders.sh diff --git a/test/web/image-stream/host-encoders.sh b/test/web/image-stream/host-encoders.sh old mode 100644 new mode 100755 From 84198b0cf2b7b91bffa3a08ded813fc5fb4f8d60 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:18:00 +0100 Subject: [PATCH 12/20] Average the codec chunk size over the chunks processed (#769) --- test/web/image-stream/bench.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/web/image-stream/bench.js b/test/web/image-stream/bench.js index d2947497..5b9f6d3b 100644 --- a/test/web/image-stream/bench.js +++ b/test/web/image-stream/bench.js @@ -128,7 +128,7 @@ canvas.width = w; canvas.height = h; const times = []; - let late = 0, bytes = 0; + let late = 0, bytes = 0, processed = 0; for (const chunk of chunks) { const output = new Promise(resolve => { awaited = {timestamp: chunk.timestamp, resolve}; }); const start = performance.now(); @@ -145,13 +145,14 @@ } else if (!broken) ++late; bytes += chunk.byteLength; + ++processed; if (broken) throw broken; if (late > 5) break; } decoder.close(); times.sort((a, b) => a - b); const at = p => times.length ? Math.round(times[Math.floor(p * (times.length - 1))] * 100) / 100 : null; - return {frames: times.length, heldBack: late, chunkBytes: Math.round(bytes / chunks.length), decodeDrawMs50: at(0.5), decodeDrawMs95: at(0.95)}; + return {frames: times.length, heldBack: late, chunkBytes: Math.round(bytes / processed), decodeDrawMs50: at(0.5), decodeDrawMs95: at(0.95)}; } await webFront.ready; From 7870095cb31548a13cfbe261c9ef99f568ac59ed Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 03:21:18 +0100 Subject: [PATCH 13/20] Keep the benchmark alive until its application has drained the work that refers to it (#769) --- test/web/ImageStreamBenchmark.cpp | 60 ++++++++++++++++++++++++------- 1 file changed, 48 insertions(+), 12 deletions(-) diff --git a/test/web/ImageStreamBenchmark.cpp b/test/web/ImageStreamBenchmark.cpp index c860f15b..f6102ce7 100644 --- a/test/web/ImageStreamBenchmark.cpp +++ b/test/web/ImageStreamBenchmark.cpp @@ -332,8 +332,9 @@ using BenchFrontend = WEBFRONT_TEST_FRONTEND; using App = webfront::BasicWFWithFrontend, BenchFrontend>; +/// The callbacks, the route and the producer of the page's cases. It outlives the application whose callbacks refer to it; +/// ProducerShutdown ends the work that uses the application while that one is still alive. class Bench { - App& app; int seconds; std::mutex runMutex; std::shared_ptr run; @@ -422,16 +423,24 @@ class Bench { } } - void stopProducer() { +public: + /// Asks the producer and the route's body to end, without waiting. Thread-safe. + void signalStop() { if (const auto state = current()) { std::scoped_lock lock(state->mutex); state->stopping = true; state->changed.notify_all(); } + } + + /// signalStop(), then joins the producer. On the server thread, or once the server has stopped. + void stopProducer() { + signalStop(); if (producer.joinable()) producer.join(); } +private: /// The streamed route: the response ends with the case. The body callback runs on a route worker, which it holds. webfront::http::RouteReply frames() { webfront::http::RouteReply reply; @@ -461,11 +470,13 @@ class Bench { } public: - webfront::http::RouteTable::Registration route; - std::string failure = "the benchmark page closed without a report"; // empty: reported + std::string failure = "the benchmark page closed without a report"; // empty: reported + + Bench(int duration, std::filesystem::path path) : seconds(duration), reportPath(std::move(path)) { } - Bench(App& application, int duration, std::filesystem::path path) : app(application), seconds(duration), reportPath(std::move(path)) { - route = app.addRoute("/frames/", [this](const webfront::http::RouteRequest&) { + /// Registers the route and the callbacks. The route is the caller's, to remove before the application is destroyed. + [[nodiscard]] webfront::http::RouteTable::Registration attach(App& app) { + auto route = app.addRoute("/frames/", [this](const webfront::http::RouteRequest&) { return frames(); }); app.cppFunction("benchProgress", [](const std::string& text) { @@ -516,7 +527,7 @@ class Bench { state->changed.notify_all(); }); // Runs the measured window after one second of warm-up and returns its figures as JSON. - app.cppFunction("benchMeasure", [this]() -> webfront::ResultTask { + app.cppFunction("benchMeasure", [this, &app]() -> webfront::ResultTask { const auto state = current(); co_await app.resumeAfter(std::chrono::seconds(1)); const auto before = cpuTimes(); @@ -556,7 +567,7 @@ class Bench { throw std::runtime_error("the host stopped sending: " + state->producerError); co_return json; }); - app.cppFunction("benchReport", [this](const std::string& json) { + app.cppFunction("benchReport", [this, &app](const std::string& json) { std::cout << "IMAGE-STREAMS " << json << std::endl; try { if (!reportPath.empty()) @@ -568,10 +579,11 @@ class Bench { app.requestClose(); }); // A page that cannot go on says so, instead of leaving its window open for ever. - app.cppFunction("benchFailed", [this](const std::string& message) { + app.cppFunction("benchFailed", [this, &app](const std::string& message) { failure = "the benchmark page failed: " + message; app.requestClose(); }); + return route; } Bench(const Bench&) = delete; @@ -581,6 +593,26 @@ class Bench { } }; +/// Ends, while the application is alive, what refers to it or to the bench: the producer is told to stop, the server is +/// stopped and its tasks drained, then the producer is joined (a callback may have started another until then). +struct ProducerShutdown { + App& app; + Bench& bench; + + ProducerShutdown(App& application, Bench& measured) : app(application), bench(measured) { } + ProducerShutdown(const ProducerShutdown&) = delete; + ProducerShutdown& operator=(const ProducerShutdown&) = delete; + ~ProducerShutdown() { + bench.signalStop(); + try { + app.shutdown(); + } catch (const std::exception& error) { + std::cerr << "image stream bench: " << error.what() << '\n'; // the application's destructor drains again + } + bench.stopProducer(); + } +}; + void dumpFrames(const std::filesystem::path& directory) { std::filesystem::create_directories(directory); for (const auto& [width, height] : { @@ -627,9 +659,13 @@ int main(int argc, char** argv) { #endif std::string failure; { - App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::absolute(positional[0])}); - Bench bench(app, seconds, positional.size() > 1 ? positional[1] : ""); - app.show("bench.html"); + Bench bench(seconds, positional.size() > 1 ? positional[1] : ""); // outlives the application's callbacks + { + App app(webfront::WebFrontConfig{.documentRoot = std::filesystem::absolute(positional[0])}); + const auto route = bench.attach(app); + const ProducerShutdown shutdown(app, bench); // last: runs first + app.show("bench.html"); + } failure = bench.failure; } if (!failure.empty()) From 54d3904882525081cb838a448305f8555856e6c7 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 09:31:42 +0100 Subject: [PATCH 14/20] Name the BareNative repository in the Jetson jobs' guard (#769) The guard compared github.repository with the former owner's repository, so the Jetson validation and the hardware workflow were skipped since the move. The runner instructions name the new repository too. --- .github/workflows/BuildAndTest.yml | 2 +- .github/workflows/JetsonOrin.yml | 2 +- docs/JETSON_RUNNER.md | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 553acb70..305a4c20 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -58,7 +58,7 @@ jobs: # Pre-merge entry point: the standalone workflow cannot be dispatched until it is on the default branch. jetson-validation: if: >- - github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && github.event_name == 'workflow_dispatch' && + github.repository == 'BareNative/WebFront' && !cancelled() && github.event_name == 'workflow_dispatch' && github.actor == 'ambroise-leclerc' && github.ref_type == 'branch' && inputs.jetson_orin runs-on: [self-hosted, linux, arm64, jetson-orin] timeout-minutes: 180 diff --git a/.github/workflows/JetsonOrin.yml b/.github/workflows/JetsonOrin.yml index 2e25d617..2ab93f91 100644 --- a/.github/workflows/JetsonOrin.yml +++ b/.github/workflows/JetsonOrin.yml @@ -17,7 +17,7 @@ concurrency: jobs: jetson-orin: if: >- - github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && + github.repository == 'BareNative/WebFront' && !cancelled() && (github.event_name == 'schedule' || (github.event_name == 'push' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && github.actor == 'ambroise-leclerc' && github.ref_type == 'branch')) runs-on: [self-hosted, linux, arm64, jetson-orin] diff --git a/docs/JETSON_RUNNER.md b/docs/JETSON_RUNNER.md index 13226fb5..e049564e 100644 --- a/docs/JETSON_RUNNER.md +++ b/docs/JETSON_RUNNER.md @@ -37,7 +37,7 @@ Before connecting the runner, require approval for **all external contributors** in Settings → Actions → General. Inspect without displaying credentials: ```sh -gh api repos/ambroise-leclerc/WebFront/actions/permissions/fork-pr-contributor-approval +gh api repos/BareNative/WebFront/actions/permissions/fork-pr-contributor-approval ``` The expected `approval_policy` is `all_external_contributors`. The earlier @@ -64,7 +64,7 @@ Download the offered `actions/runner` release, verify the supplied SHA-256 befor extracting it as the service account, then configure from the runner directory: ```sh -./config.sh --url https://github.com/ambroise-leclerc/WebFront \ +./config.sh --url https://github.com/BareNative/WebFront \ --name webfront-jetson-orin --labels linux,arm64,jetson-orin \ --work _work --unattended --token "$REGISTRATION_TOKEN" ``` From c8ac5a1999ba334658f5c2bf13acdf692850e944 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:09:34 +0100 Subject: [PATCH 15/20] Pin the BareNative repository in the hardware workflow audit (#769) The audit compares the Jetson jobs' guard with a literal copy, which still named the former owner's repository. --- test/tools/TestHardwareWorkflows.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/tools/TestHardwareWorkflows.py b/test/tools/TestHardwareWorkflows.py index 29401e76..cc16e059 100644 --- a/test/tools/TestHardwareWorkflows.py +++ b/test/tools/TestHardwareWorkflows.py @@ -26,7 +26,7 @@ jobs: jetson-orin: if: >- - github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && + github.repository == 'BareNative/WebFront' && !cancelled() && (github.event_name == 'schedule' || (github.event_name == 'push' && github.ref == 'refs/heads/master') || (github.event_name == 'workflow_dispatch' && github.actor == 'ambroise-leclerc' && github.ref_type == 'branch')) runs-on: [self-hosted, linux, arm64, jetson-orin] @@ -37,7 +37,7 @@ VALIDATION_CONTROL = """ jetson-validation: if: >- - github.repository == 'ambroise-leclerc/WebFront' && !cancelled() && github.event_name == 'workflow_dispatch' && + github.repository == 'BareNative/WebFront' && !cancelled() && github.event_name == 'workflow_dispatch' && github.actor == 'ambroise-leclerc' && github.ref_type == 'branch' && inputs.jetson_orin runs-on: [self-hosted, linux, arm64, jetson-orin] timeout-minutes: 180 @@ -110,7 +110,7 @@ def test_rejects_untrusted_routes(self): ('branches: [master]', 'branches: [develop, master]'), ("github.ref == 'refs/heads/master'", 'true'), ("github.actor == 'ambroise-leclerc'", 'true'), - ("github.repository == 'ambroise-leclerc/WebFront'", 'true'), + ("github.repository == 'BareNative/WebFront'", 'true'), ("github.ref_type == 'branch'", 'true'), ("github.event_name == 'push'", "github.event_name == 'pull_request'"), ('contents: read', 'contents: write'), From ad6aaa455f3b48d493bc3f2bb9d2989ab0262008 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:36:40 +0100 Subject: [PATCH 16/20] Consume the installed package in C++26 only with a compiler that has that mode (#769) GCC 13 refuses -std=c++26 and reports 202100 in C++23, so the C++26 consumers of the installed-layout check can never see the standard library senders. Ask the compiler and keep to C++23 when it does not go past 202302. --- test/cmake/CheckInstalledLayout.cmake | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/test/cmake/CheckInstalledLayout.cmake b/test/cmake/CheckInstalledLayout.cmake index 4b6dd02d..9eb0f1d8 100644 --- a/test/cmake/CheckInstalledLayout.cmake +++ b/test/cmake/CheckInstalledLayout.cmake @@ -140,11 +140,26 @@ function(consume name) run("${CMAKE_COMMAND}" -S "${WORK}/consumer" -B "${WORK}/${name}" ${common} ${ARGN}) endfunction() if(NOT MSVC_COMPILER) - foreach(standard 23 26) + # A compiler without a C++26 mode (GCC 13 refuses -std=c++26, and its C++23 mode reports 202100) cannot show the senders + # of C++26: ask it, and keep to C++23 when it does not go past 202302. + file(WRITE "${WORK}/mode.cpp" "__cplusplus\n") + execute_process(COMMAND "${TEST_CXX_COMPILER}" "${latest}" -E -x c++ "${WORK}/mode.cpp" + RESULT_VARIABLE mode_status OUTPUT_VARIABLE mode_output ERROR_QUIET) + set(standards 23) + set(has_26 FALSE) + if(mode_status EQUAL 0 AND mode_output MATCHES "([0-9][0-9][0-9][0-9][0-9][0-9])L" AND CMAKE_MATCH_1 GREATER 202302) + set(standards 23 26) + set(has_26 TRUE) + else() + message(STATUS "${TEST_CXX_COMPILER} has no C++26 mode: only C++23 is consumed") + endif() + foreach(standard ${standards}) consume(standard-${standard} "-DCMAKE_PREFIX_PATH=${prefix}" -DCMAKE_CXX_STANDARD=${standard} -DSTANDARD=${standard} "-DCMAKE_CXX_FLAGS=${include_flag}${stand_in}") endforeach() - consume(standard-flag "-DCMAKE_PREFIX_PATH=${prefix}" -DSTANDARD=26 "-DCMAKE_CXX_FLAGS=${latest} ${include_flag}${stand_in}") + if(has_26) + consume(standard-flag "-DCMAKE_PREFIX_PATH=${prefix}" -DSTANDARD=26 "-DCMAKE_CXX_FLAGS=${latest} ${include_flag}${stand_in}") + endif() endif() # The component WebFront alone is a complete package. From 469a38335468ba7ae87f2941079b64f3c2d19a49 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:37:07 +0100 Subject: [PATCH 17/20] Let a Jetson dispatch run the image stream measurement alone (#769) The complete validation takes more than an hour to build on the board, and an unrelated test failure stopped the script before the measurement. With jetson_orin_measure_only the job configures the WebKitGTK tree and builds only image_stream_bench. --- .github/scripts/jetson-orin.sh | 26 ++++++++++++++++---------- .github/workflows/BuildAndTest.yml | 6 ++++++ 2 files changed, 22 insertions(+), 10 deletions(-) diff --git a/.github/scripts/jetson-orin.sh b/.github/scripts/jetson-orin.sh index 3e635132..d2d3712c 100755 --- a/.github/scripts/jetson-orin.sh +++ b/.github/scripts/jetson-orin.sh @@ -39,19 +39,25 @@ common=(-G Ninja -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_ENABLE_TESTING=ON -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_SCAN_FOR_MODULES=OFF -DCMAKE_JOB_POOLS=jetson_compile=1 -DCMAKE_JOB_POOL_COMPILE=jetson_compile -DWEBFRONT_HOST_LOOP_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=87) -cmake -S . -B build-jetson-core "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=OFF -cmake --build build-jetson-core --parallel 2 -# Select one scenario directly: Bdd exits 4 if it skips for lack of a GPU. CTest permits skips. -build-jetson-core/test/unit/tests --exact 'Host loop: CUDA computes the image of the CPU, within the rounding of the device' -ctest --test-dir build-jetson-core --output-on-failure --no-tests=error --parallel 2 \ - --output-junit core-results.xml +# A maintainer's dispatch may ask for the image stream measurement alone (docs/IMAGE_STREAMS.md): no test suite is built. +measure_only=${WEBFRONT_JETSON_MEASURE_ONLY:-false} +if [[ "$measure_only" != true ]]; then + cmake -S . -B build-jetson-core "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=OFF + cmake --build build-jetson-core --parallel 2 + # Select one scenario directly: Bdd exits 4 if it skips for lack of a GPU. CTest permits skips. + build-jetson-core/test/unit/tests --exact 'Host loop: CUDA computes the image of the CPU, within the rounding of the device' + ctest --test-dir build-jetson-core --output-on-failure --no-tests=error --parallel 2 \ + --output-junit core-results.xml +fi cmake -S . -B build-jetson-webkitgtk "${common[@]}" -DWEBFRONT_EMBED_WEBKITGTK=ON \ -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK -DWEBFRONT_BUILD_EXAMPLES=OFF -cmake --build build-jetson-webkitgtk --target webtest developer_integration webfront-wf --parallel 2 -ctest --test-dir build-jetson-webkitgtk -L web-integration --output-on-failure --no-tests=error \ - --parallel 2 --output-junit webkitgtk-results.xml +if [[ "$measure_only" != true ]]; then + cmake --build build-jetson-webkitgtk --target webtest developer_integration webfront-wf --parallel 2 + ctest --test-dir build-jetson-webkitgtk -L web-integration --output-on-failure --no-tests=error \ + --parallel 2 --output-junit webkitgtk-results.xml +fi # The image stream measurement (docs/IMAGE_STREAMS.md), on a maintainer's dispatch only: figures in the log, no threshold. -if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch ]]; then +if [[ "${GITHUB_EVENT_NAME:-}" == workflow_dispatch || "$measure_only" == true ]]; then cmake --build build-jetson-webkitgtk --target image_stream_bench --parallel 2 xvfb-run -a build-jetson-webkitgtk/test/web/image_stream_bench "$PWD/test/web/image-stream" \ build-jetson-webkitgtk/image-streams-results.json diff --git a/.github/workflows/BuildAndTest.yml b/.github/workflows/BuildAndTest.yml index 305a4c20..f8893934 100644 --- a/.github/workflows/BuildAndTest.yml +++ b/.github/workflows/BuildAndTest.yml @@ -25,6 +25,10 @@ on: description: 'Also run the WebKitGTK aarch64 browser integration (GCC 13)' type: boolean default: false + jetson_orin_measure_only: + description: 'With jetson_orin: build and run only the image stream measurement, not the test suites' + type: boolean + default: false image_streams: description: 'Record the image stream measurement (docs/IMAGE_STREAMS.md) on WebView2 and WKWebView' type: boolean @@ -70,6 +74,8 @@ jobs: with: persist-credentials: false - name: Build and test at low priority + env: + WEBFRONT_JETSON_MEASURE_ONLY: ${{ inputs.jetson_orin_measure_only }} run: nice -n 15 ionice -c 3 bash .github/scripts/jetson-orin.sh - name: Retain diagnostics if: always() From 029f95677eb32f6042eb5f3e0fbeecf24f354a2b Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:47:26 +0100 Subject: [PATCH 18/20] Record the Jetson Orin Nano image stream figures and the encoder probe (#769) --- docs/IMAGE_STREAMS.md | 48 +++++++++++++++++++++++++++++++++++++++++- docs/JETSON_RUNNER.md | 6 ++++++ docs/PROJECT_STATUS.md | 4 ++-- 3 files changed, 55 insertions(+), 3 deletions(-) diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index 8d663f07..709dee21 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -107,6 +107,39 @@ WebCodecs, same method as below (median / 95th percentile): | VP9 | 2.7 / 3.2 ms | 7.3 / 8.3 ms | 27 / 53 ms | 39 / 51 ms | | H.264 baseline (Annex B) | 2.3 / 2.8 ms | 6.3 / 7.3 ms | 29 / 39 ms | 37 / 51 ms | +### Jetson Orin Nano + +Recorded on 2026-12-06 by a maintainer dispatch of the hardware validation (run 47639415990, WebKitGTK, 6 cores, +`aarch64`, JPEG encoded on the host with libjpeg, shared memory track present), one run each. **The runner is deliberately +throttled** ([JETSON_RUNNER](JETSON_RUNNER.md)): `nice 15`, idle I/O priority and a service limit of 1.5 cores, so the +host CPU column cannot exceed about 1.5 and every figure is that of a board that shares its time. The load of the board +besides the job is unknown. The figures are not comparable with the PC's. + +| Track | 960x720 at 30 fps: fps, latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | +| --- | --- | ---: | --- | ---: | +| raw-bridge | 19.4, 69.1 / 114, 0.91 + 0.53 | 21.8 | 11.2, 165 / 186, 0.72 + 0.72 | 12.6 | +| raw-route | 9.4, 182 / 271, 0.75 + 0.70 | 10.0 | 4.6, 400 / 427, 0.52 + 0.96 | 4.8 | +| jpeg-bridge | 21.0, 69.7 / 103, 1.10 + 0.34 | 21.3 | 15.6, 99.8 / 156, 1.01 + 0.45 | 15.4 | +| jpeg-route | 13.6, 107 / 171, 1.16 + 0.29 | 19.0 | 10.0, 182 / 267, 1.05 + 0.42 | 11.1 | +| raw-shared | 27.4, 9.7 / 67.0, 1.20 + 0.23 | 56.3 | 23.8, 21.8 / 76.4, 1.14 + 0.30 | 36.0 | + +libjpeg took 10 to 14 ms per frame at 960 x 720 and 34 ms at 1920 x 1080, on one thread: at 1080p the encoding alone is +the whole frame period. Drawing a JPEG took the page 30 to 42 ms and 44 to 58 ms. Frames were about the same size as on +the PC (81 KB and 238 KB). The WebCodecs test failed for VP8, VP9 and H.264 at both sizes (`EncodingError: Decode error`): +**no decoding figure** for the board. + +What the board changes in the conclusions: + +- **Holds:** the streamed route is the worst track everywhere, and shared memory the best by a wide margin. JPEG over the + bridge is the better of the two portable tracks at 1920 x 1080 (15.6 fps and 100 ms, where raw reaches 11.2 fps and + 165 ms). +- **Differs:** at 960 x 720 JPEG and raw pixels are equal here (21.0 and 19.4 fps, 70 and 69 ms), because the host encoding + and the page decoding cost what the transfer saves. **Neither portable track holds 30 images a second on the board, + even at 960 x 720**, within the CPU limit of this runner; an unthrottled board was not measured. A host that needs 30 + images a second at 1080p on this class of hardware needs more than a single libjpeg thread. +- The host used about one core in every case, up against the runner's limit, which may bound the figures; they say how + the board behaves under this limit, not what its hardware can do. + ### Encoding on the host `test/web/image-stream/host-encoders.sh` times ffmpeg 8.0.1 on the same frames (160 per size, RGBA input, conversion @@ -122,7 +155,10 @@ included), wall / CPU milliseconds per frame and bytes per frame: | h264_nvenc, h264_v4l2m2m | unavailable on this machine | unavailable | The encoders were not tuned to one quality, so sizes are not a comparison of compression. **NVENC was not measured**: this -machine has no NVIDIA GPU, and NVIDIA lists the Jetson Orin Nano without a hardware video encoder. +machine has no NVIDIA GPU, and NVIDIA lists the Jetson Orin Nano without a hardware video encoder. **On the Jetson +runner the probe found** `/dev/dri/renderD128`, `/dev/dri/renderD129` and `/dev/nvidia0`, no `nvv4l2h264enc` GStreamer +element, and no `ffmpeg`, so no encoder was timed there: NVENC, and any host video encoder on the board, stay +unmeasured. Install `ffmpeg` or a GStreamer NVIDIA plugin set on the runner to change that. ### Decoding with WebCodecs @@ -176,6 +212,16 @@ none held back. ## Running it again +On the Jetson, the full hardware validation builds for over an hour; to measure alone (about ten minutes once built), dispatch +a trusted branch with both inputs: + +```bash +gh workflow run BuildAndTest.yml --ref -f jetson_orin=true -f jetson_orin_measure_only=true +``` + +The figures are the `image stream bench:`, `IMAGE-STREAMS` and `ENCODER` lines of the job log. The same workflow records +the other engines with `-f image_streams=true`. On a workstation: + ```bash cmake -S . -B build-bench -DCMAKE_BUILD_TYPE=Release -DWEBFRONT_ENABLE_TESTING=ON -DWEBFRONT_EMBED_CEF=OFF \ -DWEBFRONT_EMBED_WEBKITGTK=ON -DWEBFRONT_WEBTEST_FRONTEND=WebKitGTK diff --git a/docs/JETSON_RUNNER.md b/docs/JETSON_RUNNER.md index e049564e..441c95bf 100644 --- a/docs/JETSON_RUNNER.md +++ b/docs/JETSON_RUNNER.md @@ -26,6 +26,12 @@ it exists on the default branch. Dispatch it with: gh workflow run BuildAndTest.yml --ref -f jetson_orin=true ``` +Add `-f jetson_orin_measure_only=true` to run only the image stream measurement ([IMAGE_STREAMS](IMAGE_STREAMS.md)) without building the test suites, which takes over an hour: + +```bash +gh workflow run BuildAndTest.yml --ref -f jetson_orin=true -f jetson_orin_measure_only=true +``` + `HardwareWorkflows` in the fast CTest tier fixes the hardware workflow's literal control plane and the manual validation job, and rejects hardware labels elsewhere. Its mutation tests cover fork PR and PR-target triggers, additional jobs, weakened ref/actor checks diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 1cd5d0d3..1e2081eb 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -31,8 +31,8 @@ WebFront is a header-only C++23 HTTP/WebSocket core plus a standalone developer and the system browser refuse it with `std::logic_error` (`app.canShowSecondaryWindow()` tells it beforehand, also after `NativeOrBrowserFrontend` fell back to the browser), and the position of the window is left to the toolkit. The call waits for the interface thread: a `cppFunction` callback runs it on `app.uiExecutor()` rather than hold the server's thread. - **Images from the host.** [The image stream example](IMAGE_STREAMS.md) sends JPEG frames (libjpeg, searched on Linux by - default) or typed-array pixels over the bridge; it is checked in the browser tests' engine. No Jetson figures: the - hardware job's repository guard skips it since the repository moved. + default) or typed-array pixels over the bridge; it is checked in the browser tests' engine. On the Jetson Orin Nano + runner neither portable track holds 30 images a second at 960 x 720; its figures are in that guide. - **Application spaces.** One process serves several independent users, each under `prefix//` with its own functions, page handlers, broadcasts and routes (`app.spaces()`, `WebFront::Space`, #671); the application owns the spaces and ends them. A space isolates dispatch, not users of one process from each other. See [spaces](SPACES.md). From f8863f7c9ff4818497338a1ee8a036d966222f61 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 11:57:42 +0100 Subject: [PATCH 19/20] Count the source ticks missed by a slow frame as skipped and never catch up (#769) --- docs/IMAGE_STREAMS.md | 11 +++++++ test/unit/CMakeLists.txt | 2 +- test/unit/ImageStreamPacingTests.cpp | 47 ++++++++++++++++++++++++++++ test/web/ImageStreamBenchmark.cpp | 20 +++++++----- test/web/ImageStreamPacing.hpp | 47 ++++++++++++++++++++++++++++ 5 files changed, 118 insertions(+), 9 deletions(-) create mode 100644 test/unit/ImageStreamPacingTests.cpp create mode 100644 test/web/ImageStreamPacing.hpp diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index 709dee21..d2f0d506 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -27,6 +27,17 @@ the example's would be; its latencies at 30 images a second are the relevant com ## What was measured +> **Pacing of the source (changed after the figures below were recorded).** The source ticks every 1/30 s. Earlier +> runs advanced the tick once per prepared frame, so when preparing a frame took longer than the period the ticks that +> went by were neither counted as skipped nor dropped, and the source could burst afterwards. The tick now moves to the +> first one in the future and the missed ticks are counted in `skippedPerSecond` +> (`test/web/ImageStreamPacing.hpp`, tested by `ImageStreamPacingTests`). **Figures recorded before this change that may +> be affected: the 30 images a second rows whose frame preparation is close to or above 33 ms, that is the Jetson +> 1920 x 1080 JPEG rows (libjpeg 34 ms) and, less, the Jetson 960 x 720 JPEG rows; their fps, skipped and latency are +> to be replaced.** The PC (encoding 2 and 6 ms) and the Windows and macOS runners (the page encodes there, the host +> only copies) prepare each frame well within the period and the maximum rate rows have no source tick, so they should +> not change; they are marked as recorded with the earlier pacing until measured again. + `image_stream_bench` (`test/web/ImageStreamBenchmark.cpp`) runs the same page in the engine of the browser tests. The host holds 16 synthetic RGBA frames (gradients, a moving checkerboard, three bits of noise in every channel) and sends them by one track; the page draws each frame, reads one pixel back, and acknowledges it. At most two frames are diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 9a171241..6ac1007a 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -79,7 +79,7 @@ list(APPEND TESTS_LIST TlsTests.cpp) list(APPEND TESTS_LIST WebKitGTKPolicyTests.cpp ContentPolicyTests.cpp HTTPServerTests.cpp HTTPEncodingTests.cpp GzipExecutorTests.cpp AcceptEncodingTests.cpp GzipTests.cpp ModuleHTTPServerTests.cpp HTTPRoutesTests.cpp HTTPKeepAliveTests.cpp HTTPRangeTests.cpp EncodingsTests.cpp WebSocketTests.cpp LoggerTests.cpp MimeTypeTests.cpp) list(APPEND TESTS_LIST FormsTests.cpp ReactStoreTests.cpp DomDocumentTests.cpp DomBatchTests.cpp JSFunctionTests.cpp TypeErasedFunctionTests.cpp MessagesTests.cpp BridgeContainersTests.cpp BridgeStructsTests.cpp BridgeBindingsTests.cpp IndexFSTests.cpp) list(APPEND TESTS_LIST FileSystemTests.cpp NativeFSTests.cpp DownloadsTests.cpp StorageTests.cpp NativeStorageTests.cpp PtyTests.cpp) -list(APPEND TESTS_LIST ImageStreamReportTests.cpp DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) +list(APPEND TESTS_LIST ImageStreamReportTests.cpp ImageStreamPacingTests.cpp DefaultFSTests.cpp StdnetShutdownTests.cpp ProfileLeaseTests.cpp SafePathTests.cpp UISubscribersTests.cpp) list(APPEND TESTS_LIST ReadBindingTests.cpp ViewAssociationTests.cpp WatchTests.cpp WatchTreeTests.cpp WatchContainersTests.cpp WatchPassTests.cpp WatchWriteTests.cpp IntrospectionTests.cpp BridgeStateTests.cpp BroadcastTests.cpp SpaceTests.cpp WebFrontTests.cpp WebLinkTests.cpp CEFPathsTests.cpp CEFMacrosTests.cpp) list(APPEND TESTS_LIST DeveloperTests.cpp WfDriverTests.cpp AutomationTests.cpp AutomationChannelTests.cpp AutomationDiscoveryTests.cpp AutomationMcpHttpTests.cpp AutomationStateTests.cpp JasmineConsumerTests.cpp HostTests.cpp LifeTests.cpp HostLoopTests.cpp StructuredShutdownTests.cpp JsFunctionSenderTests.cpp ApplicationTaskTests.cpp DeferredCallTests.cpp BridgeLightTests.cpp BridgeLightPage.cpp) list(APPEND TESTS_LIST Main.cpp ScenarioIsolation.cpp FrontendUrlTests.cpp ApplicationUrlTests.cpp FrontendContractTests.cpp UIExecutorTests.cpp NativeWindowTests.cpp WindowRegistryTests.cpp WindowControlTests.cpp CommandsTests.cpp EmbeddedCoreAssetsTests.cpp) diff --git a/test/unit/ImageStreamPacingTests.cpp b/test/unit/ImageStreamPacingTests.cpp new file mode 100644 index 00000000..755c6471 --- /dev/null +++ b/test/unit/ImageStreamPacingTests.cpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/unit +// Role: The frame source schedule of image_stream_bench: missed ticks counted, never caught up. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: a slow encoder must count its missed ticks and never burst afterwards + +#include "../web/ImageStreamPacing.hpp" +#include + +#include +#include + +using namespace webfront::bdd; +using namespace std::chrono_literals; + +namespace { +struct FakeClock { + using duration = std::chrono::nanoseconds; + using time_point = std::chrono::time_point; +}; +using Pacer = image_stream_bench::Pacer; +const auto origin = FakeClock::time_point{}; +} // namespace + +const Scenario imageStreamPacing{"The image stream source counts missed ticks and never bursts", [] { + then("a source that keeps up misses nothing", [] { + Pacer pacer(origin, 10ms); + requireEqual(pacer.advance(origin + 4ms), std::uint64_t{0}); + requireEqual(pacer.advance(origin + 12ms), std::uint64_t{0}); + require(pacer.tick() == origin + 20ms); + }); + then("a frame longer than the period counts the ticks that went by", [] { + Pacer pacer(origin, 10ms); + const auto now = origin + 34ms; + requireEqual(pacer.advance(now), std::uint64_t{3}); // ticks at 10, 20 and 30 ms + require(pacer.tick() > now); + require(pacer.tick() == origin + 40ms); + }); + then("a tick that falls exactly on the end of the work is missed, and the next is in the future", [] { + Pacer pacer(origin, 10ms); + requireEqual(pacer.advance(origin + 10ms), std::uint64_t{1}); + require(pacer.tick() == origin + 20ms); + }); + }}; diff --git a/test/web/ImageStreamBenchmark.cpp b/test/web/ImageStreamBenchmark.cpp index f6102ce7..34d72e61 100644 --- a/test/web/ImageStreamBenchmark.cpp +++ b/test/web/ImageStreamBenchmark.cpp @@ -14,6 +14,7 @@ // image_stream_bench [] [--seconds N] // image_stream_bench --dump-frames (the frames, for image-stream/host-encoders.sh) +#include "ImageStreamPacing.hpp" #include "ImageStreamReport.hpp" #include #include @@ -347,10 +348,10 @@ class Bench { } static void produce(std::shared_ptr state, App::UI ui) { - const auto period = std::chrono::nanoseconds(state->fps > 0 ? 1'000'000'000 / state->fps : 0); - auto tick = Clock::now(); - const bool jpeg = state->track.starts_with("jpeg"); - const bool route = state->track.ends_with("route"); + const auto period = std::chrono::nanoseconds(state->fps > 0 ? 1'000'000'000 / state->fps : 0); + image_stream_bench::Pacer pacer(Clock::now(), period); + const bool jpeg = state->track.starts_with("jpeg"); + const bool route = state->track.ends_with("route"); for (;;) { { std::unique_lock lock(state->mutex); @@ -358,8 +359,11 @@ class Bench { return state->stopping || static_cast(state->inFlight.size()) < state->window; }; if (state->fps > 0) { - tick += period; - state->changed.wait_until(lock, tick, [&] { + // Ticks that went by while the previous frame was prepared are skipped, not caught up. + const auto missed = pacer.advance(Clock::now()); + if (state->measuring) + state->skipped += missed; + state->changed.wait_until(lock, pacer.tick(), [&] { return state->stopping; }); if (!state->stopping && !free()) { @@ -472,7 +476,7 @@ class Bench { public: std::string failure = "the benchmark page closed without a report"; // empty: reported - Bench(int duration, std::filesystem::path path) : seconds(duration), reportPath(std::move(path)) { } + Bench(int duration, std::filesystem::path path) : seconds(duration), reportPath(std::move(path)) {} /// Registers the route and the callbacks. The route is the caller's, to remove before the application is destroyed. [[nodiscard]] webfront::http::RouteTable::Registration attach(App& app) { @@ -599,7 +603,7 @@ struct ProducerShutdown { App& app; Bench& bench; - ProducerShutdown(App& application, Bench& measured) : app(application), bench(measured) { } + ProducerShutdown(App& application, Bench& measured) : app(application), bench(measured) {} ProducerShutdown(const ProducerShutdown&) = delete; ProducerShutdown& operator=(const ProducerShutdown&) = delete; ~ProducerShutdown() { diff --git a/test/web/ImageStreamPacing.hpp b/test/web/ImageStreamPacing.hpp new file mode 100644 index 00000000..256a866b --- /dev/null +++ b/test/web/ImageStreamPacing.hpp @@ -0,0 +1,47 @@ +// SPDX-License-Identifier: Apache-2.0 OR CECILL-B +// Author: Ambroise Leclerc +// Created: 2026-12-06 +// +// WebFront — tests/web +// Role: Schedule of the benchmark's frame source: one tick per period, missed ticks counted, never caught up. +// Thread: worker-safe | Alloc: zero-hot-path +// LLM: benchmark support; a source slower than its period must report skipped ticks, not burst + +#pragma once + +#include +#include + +namespace image_stream_bench { + +/// Ticks of a source at a fixed rate. When preparing a frame takes longer than the period, the ticks that went by are +/// reported as missed and the next tick is the first one in the future: the source never bursts to catch up. +template +class Pacer { +public: + using Duration = typename Clock::duration; + using TimePoint = typename Clock::time_point; + + Pacer(TimePoint start, Duration period) : tick_(start), period_(period) {} + + /// Moves to the next tick, given the time `now` at which the previous work ended. Returns how many ticks had already + /// passed (and are lost); `tick()` is then strictly after `now` when missed, or the regular next tick otherwise. + [[nodiscard]] std::uint64_t advance(TimePoint now) { + tick_ += period_; + if (period_ <= Duration::zero() || tick_ > now) + return 0; + const auto missed = static_cast((now - tick_) / period_) + 1; + tick_ += period_ * static_cast(missed); + return missed; + } + + [[nodiscard]] TimePoint tick() const { + return tick_; + } + +private: + TimePoint tick_; + Duration period_; +}; + +} // namespace image_stream_bench From 8c09c738de133608a2883b392f80eef71e7e5cc8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sun, 6 Dec 2026 12:07:22 +0100 Subject: [PATCH 20/20] Record the image stream figures measured with the corrected pacing (#769) --- docs/IMAGE_STREAMS.md | 156 +++++++++++++++++++++++------------------- 1 file changed, 87 insertions(+), 69 deletions(-) diff --git a/docs/IMAGE_STREAMS.md b/docs/IMAGE_STREAMS.md index d2f0d506..a2572b89 100644 --- a/docs/IMAGE_STREAMS.md +++ b/docs/IMAGE_STREAMS.md @@ -19,24 +19,22 @@ build/examples/WebFrontImageStream --raw # the typed-array fallback - JPEG is encoded with libjpeg, searched by default on Linux only (`-DWEBFRONT_IMAGE_STREAM_JPEG=ON` elsewhere, with a libjpeg of your toolchain). Without it, or when the page cannot decode, the pixels are sent as they are. - Which format is faster depends on the engine and the machine. Under WebKitGTK, CEF and WebView2, JPEG had the lower - latency; on the hosted macOS runner, where WKWebView decoded a JPEG slowly, raw pixels did as well at 960 x 720 and - better at 1920 x 1080 (see below). Measure on your target; `--raw` is one option away. + latency; on the hosted macOS runner, where WKWebView decoded a JPEG slowly, raw pixels had the lower latency and the + higher maximum rate, and delivered more images at 1920 x 1080, though fewer at 960 x 720 and 30 images a second in the last run (see below). Measure on your target; `--raw` is one option away. The example asks for one image at a time. The benchmark keeps two in flight, so its throughput figures are higher than the example's would be; its latencies at 30 images a second are the relevant comparison. ## What was measured -> **Pacing of the source (changed after the figures below were recorded).** The source ticks every 1/30 s. Earlier -> runs advanced the tick once per prepared frame, so when preparing a frame took longer than the period the ticks that -> went by were neither counted as skipped nor dropped, and the source could burst afterwards. The tick now moves to the -> first one in the future and the missed ticks are counted in `skippedPerSecond` -> (`test/web/ImageStreamPacing.hpp`, tested by `ImageStreamPacingTests`). **Figures recorded before this change that may -> be affected: the 30 images a second rows whose frame preparation is close to or above 33 ms, that is the Jetson -> 1920 x 1080 JPEG rows (libjpeg 34 ms) and, less, the Jetson 960 x 720 JPEG rows; their fps, skipped and latency are -> to be replaced.** The PC (encoding 2 and 6 ms) and the Windows and macOS runners (the page encodes there, the host -> only copies) prepare each frame well within the period and the maximum rate rows have no source tick, so they should -> not change; they are marked as recorded with the earlier pacing until measured again. +> **Pacing of the source.** The source ticks every 1/30 s. When preparing a frame takes longer than the period, the ticks +> that went by are counted as skipped and the next frame waits for the first tick in the future, with no burst +> afterwards (`test/web/ImageStreamPacing.hpp`, tested by `ImageStreamPacingTests`). The first Jetson run, the PC +> figures (WebKitGTK and CEF) and the first WebView2 and WKWebView runs were recorded with an earlier pacing that +> advanced the tick once per frame, so a slow frame could be followed by a burst and its missed ticks were not counted. +> The Jetson, WebView2 and WKWebView tables below were recorded again with the current pacing; the **PC tables were not** +> (their frames take 2 and 6 ms to prepare against a 33 ms period, so they are not expected to change, but that was not +> checked). `image_stream_bench` (`test/web/ImageStreamBenchmark.cpp`) runs the same page in the engine of the browser tests. The host holds 16 synthetic RGBA frames (gradients, a moving checkerboard, three bits of noise in every channel) and sends @@ -86,68 +84,90 @@ and 6 ms per frame; drawing it took the page 3 to 5 ms and 10 to 12 ms. ### WebView2 and WKWebView (hosted runners) -Recorded on 2026-12-06 by the `image_streams` dispatch of `BuildAndTest.yml`, Release builds, one run each, on GitHub's -hosted virtual machines: `windows-2025` (4 logical processors reported to the page, Edge WebView2 158) and `macos-26` -(3 reported, system WKWebView). Their GPU and the load of their physical hosts are unknown, so **do not compare these -figures with the tables above**. Neither host had a JPEG library: the page encoded the JPEG frames once, beforehand, so -**the latencies contain no encoding time** and are not comparable with the JPEG latencies above either. There is no -shared memory track, and on macOS the engine's CPU is not measured. +Recorded on 2026-12-06 by the `image_streams` dispatch of `BuildAndTest.yml` at the commit that fixed the pacing (the +figures of the first, earlier run were replaced), Release builds, one run each, on GitHub's hosted virtual machines: +`windows-2025` (4 logical processors reported to the page, Edge WebView2 158) and `macos-26` (3 reported, system +WKWebView). Their GPU and the load of their physical hosts are unknown, so **do not compare these figures with the tables +above**. Neither host had a JPEG library: the page encoded the JPEG frames once, beforehand, so **the latencies contain no +encoding time** and are not comparable with the JPEG latencies above either. There is no shared memory track, and on +macOS the engine's CPU is not measured. Latency is the median / 95th percentile in milliseconds; CPU is host + engine +(host only on macOS). -| Track, WebView2 | 960x720 at 30 fps: latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | +| Track, WebView2 | 960x720 at 30 fps: fps, latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | | --- | --- | ---: | --- | ---: | -| raw-bridge | 4.5 / 10.2, 0.02 + 0.21 | 218 | 30.0, 11.9 / 14.2, 0.07 + 0.49 | 76 | -| raw-route | 10.5 / 12.1, 0.32 + 0.57 | 98 | 30.0, 31.9 / 36.6, 1.08 + 1.61 | 32 | -| jpeg-bridge | 3.3 / 3.7, 0.02 + 0.13 | 405 | 30.0, 7.3 / 7.8, 0.02 + 0.26 | 147 | -| jpeg-route | 3.3 / 3.6, 0.02 + 0.15 | 396 | 30.0, 7.5 / 8.1, 0.04 + 0.29 | 149 | +| raw-bridge | 30.0, 6.2 / 10.7, 0.03 + 0.29 | 140 | 30.0, 17.5 / 21.9, 0.06 + 0.69 | 53.5 | +| raw-route | 30.0, 20.1 / 21.2, 0.66 + 1.10 | 50.4 | 17.2, 102 / 116, 1.14 + 1.77 | 17.2 | +| jpeg-bridge | 30.2, 3.3 / 3.5, 0.01 + 0.15 | 352 | 30.0, 7.9 / 8.3, 0.01 + 0.32 | 136 | +| jpeg-route | 30.2, 3.6 / 3.8, 0.02 + 0.15 | 346 | 30.0, 8.7 / 9.1, 0.06 + 0.35 | 133 | -| Track, WKWebView | 960x720 at 30 fps: fps, latency, host CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, host CPU | 1920x1080 max fps | +| Track, WKWebView | 960x720 at 30 fps: fps, latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | | --- | --- | ---: | --- | ---: | -| raw-bridge | 28.0, 17.0 / 31.0, 0.09 | 110 | 28.2, 24.6 / 41.0, 0.13 | 50 | -| raw-route | 25.4, 32.8 / 105, 0.45 | 32 | 12.6, 158 / 176, 0.60 | 10 | -| jpeg-bridge | 28.4, 18.1 / 42.2, 0.04 | 52 | 29.4, 34.6 / 72.3, 0.04 | 30 | -| jpeg-route | 17.2, 47.7 / 169, 0.04 | stalled | 24.6, 67.3 / 84.3, 0.10 | 31 | +| raw-bridge | 19.4, 12.6 / 49.5, 0.06 | 86.0 | 29.2, 26.6 / 38.5, 0.12 | 45.6 | +| raw-route | 7.8, 44.6 / 120, 0.14 | 34.8 | 14.2, 134 / 161, 0.61 | 12.8 | +| jpeg-bridge | 24.6, 17.9 / 31.5, 0.03 | 52.0 | 22.6, 81.3 / 112, 0.04 | 21.0 | +| jpeg-route | 22.6, 53.9 / 111, 0.06 | 45.8 | 0.8, 93.5 / 96.1, 0.01 | 20.6 | + +The two hosted runs differ from the first ones that were recorded (before the pacing change) by more than a change of +pacing explains: on WKWebView, raw-bridge at 960 x 720 and 30 images a second went from 28.0 to 19.4 fps and +jpeg-route at 1920 x 1080 from 24.6 to **0.8 fps**, a stall like the one of the unpaced 960 x 720 JPEG route under +WebKitGTK; on WebView2 the latencies moved by a millisecond or two and raw-route at 1920 x 1080 and 30 images a second +went from 30.0 to 17.2 fps. Read the hosted figures as orders of magnitude. The JPEG frames each engine encoded at "quality 0.85" differ in size: 53 KB and 153 KB under WebView2, 155 KB and 461 KB -under WKWebView. Drawing one took 2.5 ms and 6.5 ms under WebView2, 16 ms and 31 ms under WKWebView. +under WKWebView. Drawing one took 2.8 ms and 7 ms under WebView2, 17 ms and 42 to 46 ms under WKWebView. WebCodecs, same method as below (median / 95th percentile): | Codec | WebView2 960x720 | WebView2 1920x1080 | WKWebView 960x720 | WKWebView 1920x1080 | | --- | --- | --- | --- | --- | -| VP8 | 2.9 / 3.3 ms | 7.7 / 8.7 ms | 41 / 70 ms | 46 / 77 ms | -| VP9 | 2.7 / 3.2 ms | 7.3 / 8.3 ms | 27 / 53 ms | 39 / 51 ms | -| H.264 baseline (Annex B) | 2.3 / 2.8 ms | 6.3 / 7.3 ms | 29 / 39 ms | 37 / 51 ms | +| VP8 | 2.5 / 3.0 ms | 8.0 / 9.3 ms | 43 / 55 ms | 49 / 64 ms | +| VP9 | 3.4 / 4.2 ms | 8.6 / 9.8 ms | 40 / 62 ms | 50 / 79 ms | +| H.264 baseline (Annex B) | 3.0 / 3.9 ms | 7.1 / 8.4 ms | 33 / 51 ms | 44 / 73 ms | ### Jetson Orin Nano -Recorded on 2026-12-06 by a maintainer dispatch of the hardware validation (run 47639415990, WebKitGTK, 6 cores, -`aarch64`, JPEG encoded on the host with libjpeg, shared memory track present), one run each. **The runner is deliberately -throttled** ([JETSON_RUNNER](JETSON_RUNNER.md)): `nice 15`, idle I/O priority and a service limit of 1.5 cores, so the -host CPU column cannot exceed about 1.5 and every figure is that of a board that shares its time. The load of the board -besides the job is unknown. The figures are not comparable with the PC's. +Recorded on 2026-12-06 by two maintainer dispatches of the hardware validation (WebKitGTK, 6 cores, `aarch64`, JPEG +encoded on the host with libjpeg, shared memory track present). The table is the second run, made with the current +pacing; the first run, made with the earlier one, is compared below. **The runner is deliberately throttled** +([JETSON_RUNNER](JETSON_RUNNER.md)): `nice 15`, idle I/O priority and a service limit of 1.5 cores, so the host CPU column +cannot exceed about 1.5 and every figure is that of a board that shares its time. The load of the board besides the job is +unknown. The figures are not comparable with the PC's. | Track | 960x720 at 30 fps: fps, latency, CPU | 960x720 max fps | 1920x1080 at 30 fps: fps, latency, CPU | 1920x1080 max fps | | --- | --- | ---: | --- | ---: | -| raw-bridge | 19.4, 69.1 / 114, 0.91 + 0.53 | 21.8 | 11.2, 165 / 186, 0.72 + 0.72 | 12.6 | -| raw-route | 9.4, 182 / 271, 0.75 + 0.70 | 10.0 | 4.6, 400 / 427, 0.52 + 0.96 | 4.8 | -| jpeg-bridge | 21.0, 69.7 / 103, 1.10 + 0.34 | 21.3 | 15.6, 99.8 / 156, 1.01 + 0.45 | 15.4 | -| jpeg-route | 13.6, 107 / 171, 1.16 + 0.29 | 19.0 | 10.0, 182 / 267, 1.05 + 0.42 | 11.1 | -| raw-shared | 27.4, 9.7 / 67.0, 1.20 + 0.23 | 56.3 | 23.8, 21.8 / 76.4, 1.14 + 0.30 | 36.0 | - -libjpeg took 10 to 14 ms per frame at 960 x 720 and 34 ms at 1920 x 1080, on one thread: at 1080p the encoding alone is -the whole frame period. Drawing a JPEG took the page 30 to 42 ms and 44 to 58 ms. Frames were about the same size as on -the PC (81 KB and 238 KB). The WebCodecs test failed for VP8, VP9 and H.264 at both sizes (`EncodingError: Decode error`): -**no decoding figure** for the board. - -What the board changes in the conclusions: - -- **Holds:** the streamed route is the worst track everywhere, and shared memory the best by a wide margin. JPEG over the - bridge is the better of the two portable tracks at 1920 x 1080 (15.6 fps and 100 ms, where raw reaches 11.2 fps and - 165 ms). -- **Differs:** at 960 x 720 JPEG and raw pixels are equal here (21.0 and 19.4 fps, 70 and 69 ms), because the host encoding - and the page decoding cost what the transfer saves. **Neither portable track holds 30 images a second on the board, - even at 960 x 720**, within the CPU limit of this runner; an unthrottled board was not measured. A host that needs 30 - images a second at 1080p on this class of hardware needs more than a single libjpeg thread. +| raw-bridge | 18.0, 90.2 / 109, 0.95 + 0.49 | 23.4 | 11.8, 151 / 194, 0.70 + 0.76 | 12.6 | +| raw-route | 9.8, 183 / 257, 0.75 + 0.71 | 10.0 | 4.9, 379 / 469, 0.50 + 0.96 | 5.0 | +| jpeg-bridge | 17.4, 60.2 / 87.6, 1.14 + 0.31 | 22.8 | 13.2, 98.6 / 173, 1.03 + 0.40 | 16.0 | +| jpeg-route | 14.2, 111 / 181, 1.13 + 0.31 | 18.0 | 9.8, 189 / 248, 1.06 + 0.41 | 11.0 | +| raw-shared | 21.0, 9.7 / 75.6, 1.24 + 0.20 | 58.9 | 24.9, 16.8 / 72.2, 1.12 + 0.32 | 35.3 | + +libjpeg took 12 to 19 ms per frame at 960 x 720 and 31 to 38 ms at 1920 x 1080, on one thread: at 1080p the encoding alone +is the whole frame period or more, and the missed ticks show in the skipped column (16 a second for jpeg-bridge). Drawing +a JPEG took the page 22 to 42 ms and 45 to 54 ms. Frames were about the same size as on the PC (81 KB and 238 KB). The +WebCodecs test failed for VP8, VP9 and H.264 at both sizes (`EncodingError: Decode error`): **no decoding figure** for the +board. + +**Spread.** The two runs were separated by the pacing change, so they are not a pure repeat, but they show how far one +figure can be trusted. At the maximum rate, where no source tick applies, the fps moved by 0 to 12 % (raw-bridge 960 x 720 +21.8 and 23.4, jpeg-bridge 1080p 15.4 and 16.0, raw-shared 960 x 720 56.3 and 58.9, raw-shared 1080p 36.0 and 35.3, jpeg-route +1080p 11.1 and 11.0). At 30 images a second the fps moved more, by up to 23 %: raw-shared 960 x 720 27.4 then 21.0, +jpeg-bridge 960 x 720 21.0 then 17.4, jpeg-bridge 1080p 15.6 then 13.2, raw-bridge 960 x 720 19.4 then 18.0; the host's +encoding time itself varied from 10 to 19 ms between the runs for the same 960 x 720 case. Latency medians moved by up to +30 % (raw-bridge 960 x 720 69 then 90 ms, jpeg-bridge 960 x 720 70 then 60 ms). Treat a difference smaller than about 25 % +between two cells as noise, and the order of tracks, not a figure, as the result. + +What the board does to the conclusions (both runs agree on each): + +- **Holds:** the streamed route is the worst track everywhere (4.9 to 10 fps raw, 9.8 to 14 fps JPEG at 30 images a second), + and shared memory the best by a wide margin (latency 10 to 17 ms where the others take 60 to 380 ms, and 35 to 59 fps + at the maximum rate). JPEG over the bridge is the better of the two portable tracks at 1920 x 1080: 13.2 fps and 99 ms + where raw reaches 11.8 fps and 151 ms (15.6 and 11.2 fps in the first run), and about equal in throughput at the maximum + rate (16.0 against 12.6). +- **Differs:** at 960 x 720 JPEG and raw pixels have the same frame rate here (17.4 and 18.0 fps at 30 images a second, 22.8 + and 23.4 at the maximum), JPEG with the lower latency (60 against 90 ms) because the host encoding and the page decoding + cost what the transfer saves. **Neither portable track holds 30 images a second on the board, even at 960 x 720**, within + the CPU limit of this runner; an unthrottled board was not measured. A host that needs 30 images a second at 1080p on this + class of hardware needs more than a single libjpeg thread. - The host used about one core in every case, up against the runner's limit, which may bound the figures; they say how the board behaves under this limit, not what its hardware can do. @@ -177,9 +197,9 @@ The page encodes 90 frames with the engine's `VideoEncoder`, then times each fro same timestamp, one at a time (median / 95th percentile); a frame not given within 250 ms is counted as held back and not timed. The content differs from the frames above. -The figures here and for WebView2 and WKWebView were recorded before the page matched outputs by timestamp. They are not -affected: a wrong match needed a held-back frame first, and every codec that decoded gave all 90 outputs in time, with -none held back. +The WebKitGTK and CEF figures here were recorded before the page matched outputs by timestamp. They are not affected: a +wrong match needed a held-back frame first, and every codec that decoded gave all 90 outputs in time, with none held +back. The WebView2 and WKWebView figures above were recorded with the matching. | Codec | WebKitGTK 960x720 | WebKitGTK 1920x1080 | CEF 960x720 | CEF 1920x1080 | | --- | --- | --- | --- | --- | @@ -196,10 +216,10 @@ none held back. fails on the stream its own encoder produced; whether another H.264 stream decodes was not tried) nor the CEF build. Reconsider it for a remote browser on a narrow link. - **Streamed route.** It depends on the engine. Under WebView2 and CEF its JPEG figures equal the bridge's. Under - WKWebView it fell behind (17 and 25 images a second where 30 were asked, and the same stall of the unpaced 960 x 720 - JPEG case as under WebKitGTK). In WebKitGTK, at 30 images a second, a frame arrived about one frame period later than - over the bridge, as if the end of each frame were held until more data came, and the unpaced 960 x 720 JPEG case - stalled. Both WebKit engines being affected points to WebKit's side of the exchange; the cause was not identified. + WKWebView it fell behind (23 and 0.8 images a second at 30 asked for JPEG, the second being a stall, and 8 and 14 + for raw; in the first hosted run 17 and 25 for JPEG). In WebKitGTK, at 30 images a second, a frame arrived about one + frame period later than over the bridge, as if the end of each frame were held until more data came, and the unpaced + 960 x 720 JPEG case stalled. Both WebKit engines being affected points to WebKit's side of the exchange; the cause was not identified. Raw frames were slower than over the bridge in all four engines (the server sends a route's body in chunks of 8 KiB, each read on a worker thread, which may explain it). One viewer also holds one of the 4 route worker threads for as long as it watches ([HTTP_ASSETS](HTTP_ASSETS.md#streaming-and-dynamic-routes-454)). @@ -214,11 +234,9 @@ none held back. ## Not measured -- **Jetson Orin Nano: no figures.** The measurement is part of the manual hardware validation - ([JETSON_RUNNER](JETSON_RUNNER.md)), but its job was skipped when dispatched: its guard still requires the repository - name `ambroise-leclerc/WebFront`, which no longer matches since the move to BareNative. Changing that guard is a - maintainer's decision. -- Host-side JPEG encoding on Windows and macOS, and the engine's CPU on macOS. +- **Video encoders on the Jetson** (see above), WebCodecs decoding on the Jetson, and the board without the runner's + CPU limit. +- Host-side JPEG encoding on Windows and macOS (the page encoded there), and the engine's CPU on macOS. - A GPU-accelerated display, a physical screen, a browser on another machine. ## Running it again