diff --git a/CMakeLists.txt b/CMakeLists.txt index 0cc950a9..5e8d45d6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -248,6 +248,9 @@ apply_managed_component_patch(patches/esp_h264-1.4.0-external-db.patch) # An access unit that overflows its output buffer raises the minimum QP, so # the next IDR fits instead of overflowing at the same QP every second. apply_managed_component_patch(patches/esp_h264-1.4.1-overflow-qp.patch) +# The average QP of each frame for /webrtc/stats, and the QP range that the +# bench-only encoder toggles set (CONFIG_JETKVM_VIDEO_TUNING). +apply_managed_component_patch(patches/esp_h264-1.4.1-frame-qp.patch) # These three libSRTP patches stack on the same CMakeLists, so an earlier one # cannot reverse-check once a later one is applied. Detect the final state. set(_srtp_component_cmake diff --git a/Dockerfile b/Dockerfile index 80da8da6..0449107f 100644 --- a/Dockerfile +++ b/Dockerfile @@ -7,10 +7,11 @@ # docker buildx build --build-arg VERSION= --build-arg BOARD= \ # [--build-arg MOCK_CLOUD_JWKS_URL=] [--build-arg WIFI_SETUP_LOG_CODE=1] \ # [--build-arg USB_DEBUGGING=1] [--build-arg MEMORY_OWNERS=1] \ -# --output type=local,dest= . +# [--build-arg VIDEO_TUNING=1] --output type=local,dest= . # # USB_DEBUGGING=1 keeps the USB Serial/JTAG port on by default. # MEMORY_OWNERS=1 counts heap bytes per task (components/jetkvm_memory_owners). +# VIDEO_TUNING=1 lets /webrtc/stats set encoder toggles (tools/sprites). # # gets jetkvm-mini.bin (the update image) plus what # tools/e2e/serial_flash.sh writes over USB: bootloader.bin, @@ -47,6 +48,7 @@ ARG MOCK_CLOUD_JWKS_URL= ARG WIFI_SETUP_LOG_CODE=0 ARG USB_DEBUGGING=0 ARG MEMORY_OWNERS=0 +ARG VIDEO_TUNING=0 # A fresh tree's first configure stops once and asks for another run # (CMakeLists.txt). The Component Manager does not lock its cache, so only one # configure at a time may hold it. @@ -64,6 +66,11 @@ RUN --mount=type=cache,target=/component-cache,sharing=locked \ 1) echo CONFIG_JETKVM_MEMORY_OWNERS=y >> /tmp/bench.defaults ;; \ *) echo "MEMORY_OWNERS must be 0 or 1" >&2; exit 1 ;; \ esac && \ + case "$VIDEO_TUNING" in \ + 0) ;; \ + 1) echo CONFIG_JETKVM_VIDEO_TUNING=y >> /tmp/bench.defaults ;; \ + *) echo "VIDEO_TUNING must be 0 or 1" >&2; exit 1 ;; \ + esac && \ if [ -s /tmp/bench.defaults ]; then \ defaults=("-DSDKCONFIG_DEFAULTS=/src/sdkconfig.defaults;/tmp/bench.defaults"); \ fi && \ diff --git a/components/jetkvm_video/jetkvm_video.c b/components/jetkvm_video/jetkvm_video.c index 4bfec479..71232e32 100644 --- a/components/jetkvm_video/jetkvm_video.c +++ b/components/jetkvm_video/jetkvm_video.c @@ -59,6 +59,7 @@ #include "jetkvm_video.h" #include "jetkvm_video_helpers.h" #include "jetkvm_video_quality.h" +#include "jetkvm_video_tuning.h" #include "video_encode_totals.h" #include "hdmi_hpd_retry.h" #include "hdmi_bridge_fault.h" @@ -405,6 +406,9 @@ typedef struct { uint8_t h264_fps; uint8_t h264_gop; uint32_t h264_bitrate; +#if CONFIG_JETKVM_VIDEO_TUNING + uint8_t h264_qp_max; +#endif /* The transport refused the encoder's mode; cleared by csi_destroy(). */ bool h264_mode_refused; esp_h264_raw_format_t h264_pic_type; @@ -1538,7 +1542,8 @@ static void video_metrics_record_frame(app_ctx_t *ctx, bool keyframe, bool sink_accepted, int64_t csi_dma_eof_timestamp_us, - int64_t h264_encode_start_timestamp_us) + int64_t h264_encode_start_timestamp_us, + uint32_t qp_x100) { uint32_t handoff_us = 0; if (h264_encode_start_timestamp_us >= csi_dma_eof_timestamp_us) { @@ -1583,7 +1588,7 @@ static void video_metrics_record_frame(app_ctx_t *ctx, } video_encode_totals_add(&s_video_encode_totals, h264_encode_start_timestamp_us + encode_time_us, - keyframe, encode_time_us, handoff_us); + keyframe, encode_time_us, handoff_us, qp_x100); portEXIT_CRITICAL(&s_video_metrics_mux); } @@ -1603,6 +1608,8 @@ void jetkvm_video_get_encode_stats(webrtc_transport_video_encode_t *encode) .idr_encode_max_us = longest.idr_encode_us, .handoff_us = totals.handoff_us, .handoff_max_us = longest.handoff_us, + .qp_x100_sum = totals.qp_x100_sum, + .coarse_frames = totals.coarse_frames, }; } @@ -1925,11 +1932,40 @@ static uint32_t h264_target_bitrate(uint16_t width, uint16_t height, return bitrate; } +#if CONFIG_JETKVM_VIDEO_TUNING +static void h264_hw_apply_qp_max(app_ctx_t *ctx) +{ + const uint32_t tuned = jetkvm_video_tuning_qp_max(); + const uint8_t qp_max = tuned ? (uint8_t)tuned : ESP_H264_QP_MAX; + if (qp_max == ctx->h264_qp_max) { + return; + } + const uint8_t qp_min = qp_max < H264_QUALITY_QP_MIN ? + qp_max : H264_QUALITY_QP_MIN; + if (esp_h264_enc_hw_set_qp_range(ctx->h264_enc, qp_min, qp_max) != + ESP_H264_ERR_OK) { + ESP_LOGE(TAG, "h264hw: QP range %u-%u failed", (unsigned)qp_min, + (unsigned)qp_max); + return; + } + ESP_LOGI(TAG, "h264hw: maximum QP %u -> %u", + (unsigned)ctx->h264_qp_max, (unsigned)qp_max); + ctx->h264_qp_max = qp_max; +} +#endif + static bool h264_hw_update_quality(app_ctx_t *ctx) { const uint32_t quality_permille = jetkvm_video_quality_get_permille(); - const uint32_t ceiling = h264_target_bitrate( + uint32_t ceiling = h264_target_bitrate( ctx->h264_width, ctx->h264_height, ctx->h264_fps, quality_permille); +#if CONFIG_JETKVM_VIDEO_TUNING + h264_hw_apply_qp_max(ctx); + const uint32_t tuned_rate_kbps = jetkvm_video_tuning_rate_kbps(); + if (tuned_rate_kbps) { + ceiling = tuned_rate_kbps * 1000U; + } +#endif /* Only Auto follows receiver feedback; a manual preset is a fixed rate. */ const bool adaptive = quality_permille == JETKVM_VIDEO_QUALITY_AUTO_PERMILLE; @@ -2073,6 +2109,9 @@ static esp_err_t h264_hw_ensure(app_ctx_t *ctx, uint16_t width, uint16_t height, ctx->h264_fps = configured_fps; ctx->h264_gop = configured_gop; ctx->h264_bitrate = bitrate; +#if CONFIG_JETKVM_VIDEO_TUNING + ctx->h264_qp_max = ESP_H264_QP_MAX; +#endif ctx->h264_pic_type = pic_type; ctx->h264_serial_dumped = false; ESP_LOGI(TAG, "h264hw: ready %ux%u@%u %s gop=%u bitrate=%" PRIu32 " out=%" PRIu32, @@ -2381,6 +2420,8 @@ static void h264_pipeline_encode_one(app_ctx_t *ctx, goto cancel_output; } + uint32_t qp_x100 = 0; + esp_h264_enc_hw_get_frame_qp_x100(ctx->h264_enc, &qp_x100); bool keyframe = out_frame.frame_type == ESP_H264_FRAME_TYPE_IDR; /* Only this task writes encode_frames; the frame is counted below. */ app_h264_frame_meta_t meta = { @@ -2405,7 +2446,7 @@ static void h264_pipeline_encode_one(app_ctx_t *ctx, rtc_reserved = false; /* Commit consumes the lease even when rejected. */ video_metrics_record_frame(ctx, encode_time_us, capture_sequence, out_frame.length, keyframe, sink_accepted, - capture_timestamp_us, start_us); + capture_timestamp_us, start_us, qp_x100); if (!sink_accepted) { goto cancel_output; } diff --git a/components/jetkvm_video/tests/test_encode_totals.py b/components/jetkvm_video/tests/test_encode_totals.py index f86636c0..283f91c2 100644 --- a/components/jetkvm_video/tests/test_encode_totals.py +++ b/components/jetkvm_video/tests/test_encode_totals.py @@ -37,9 +37,9 @@ /* The first frames come long after boot. Each type has its count, its * sum and its longest time; the handoff is over both types. */ const int64_t start = 5 * W + 123; - video_encode_totals_add(&totals, start, false, 33000, 100); - video_encode_totals_add(&totals, start + 33000, true, 27000, 300); - video_encode_totals_add(&totals, start + 66000, false, 32000, 200); + video_encode_totals_add(&totals, start, false, 33000, 100, 2800); + video_encode_totals_add(&totals, start + 33000, true, 27000, 300, 2800); + video_encode_totals_add(&totals, start + 66000, false, 32000, 200, 2800); assert(totals.p_frames == 2 && totals.p_encode_us == 65000); assert(totals.idr_frames == 1 && totals.idr_encode_us == 27000); assert(totals.handoff_us == 600); @@ -47,13 +47,13 @@ /* The next window follows at once. Its shorter frame does not hide the * longest times of the window before, up to the window's last moment. */ - video_encode_totals_add(&totals, start + W, false, 31000, 50); + video_encode_totals_add(&totals, start + W, false, 31000, 50, 2800); assert_longest(start + W, 33000, 27000, 300); assert_longest(start + 2 * W - 1, 33000, 27000, 300); /* A frame of the third window ends the first: its times are gone, and * no keyframe is left in the two windows. */ - video_encode_totals_add(&totals, start + 2 * W, false, 30000, 40); + video_encode_totals_add(&totals, start + 2 * W, false, 30000, 40, 2800); assert_longest(start + 2 * W, 31000, 0, 50); /* Encoding stops. The last window's times stay for one more window @@ -66,21 +66,27 @@ assert(totals.idr_frames == 1 && totals.handoff_us == 690); /* Encoding starts again later: no time of the old windows comes back. */ - video_encode_totals_add(&totals, start + 20 * W + 7, true, 28000, 10); + video_encode_totals_add(&totals, start + 20 * W + 7, true, 28000, 10, 2800); assert_longest(start + 20 * W + 7, 0, 28000, 10); assert_longest(start + 21 * W + 6, 0, 28000, 10); - video_encode_totals_add(&totals, start + 21 * W + 7, false, 29000, 20); + video_encode_totals_add(&totals, start + 21 * W + 7, false, 29000, 20, 2800); assert_longest(start + 21 * W + 7, 29000, 28000, 20); /* The sums do not wrap at 32 bits (about 71 minutes of encode time). */ video_encode_totals_t wide = {0}; for (int frame = 0; frame < 3; ++frame) { - video_encode_totals_add(&wide, frame, false, UINT32_MAX, UINT32_MAX); + video_encode_totals_add(&wide, frame, false, UINT32_MAX, UINT32_MAX, 0); } assert(wide.p_encode_us == 3 * (uint64_t)UINT32_MAX); assert(wide.handoff_us == 3 * (uint64_t)UINT32_MAX); - puts("encoder totals since boot: sums per type, longest of two windows: PASS"); + /* A frame at an average QP of 50 is coarse; one just below is not. */ + video_encode_totals_t qp = {0}; + video_encode_totals_add(&qp, 0, false, 0, 0, 4999); + video_encode_totals_add(&qp, 1, true, 0, 0, 5000); + assert(qp.qp_x100_sum == 9999 && qp.coarse_frames == 1); + + puts("encoder totals since boot: sums per type, longest of two windows, QP: PASS"); return 0; } """ diff --git a/components/jetkvm_video/tests/test_output_reservation.py b/components/jetkvm_video/tests/test_output_reservation.py index 1d646c9f..c89c6dfc 100644 --- a/components/jetkvm_video/tests/test_output_reservation.py +++ b/components/jetkvm_video/tests/test_output_reservation.py @@ -138,7 +138,7 @@ def structure(name): uint32_t pending_sync, last_completed_sync; bool last_completed_success; int encode_result; - uint32_t encoded_length; + uint32_t encoded_length, frame_qp_x100; int64_t now_us; app_h264_frame_meta_t committed_meta; } state; @@ -252,6 +252,12 @@ def structure(name): state.applied_bitrate = bitrate; return ESP_H264_ERR_OK; } +static esp_h264_err_t esp_h264_enc_hw_get_frame_qp_x100(void *encoder, uint32_t *qp_x100) +{ + assert(encoder == &encoder_param && !lock_depth && state.encodes > 0); + *qp_x100 = state.frame_qp_x100; + return ESP_H264_ERR_OK; +} static esp_h264_err_t esp_h264_enc_force_idr(int *base) { assert(base == &encoder_param.base); @@ -470,6 +476,7 @@ def structure(name): /* A successful IDR and P frame both use the lease throughout encoding. */ ctx = reset(); state.pending_sync = 41; + state.frame_qp_x100 = 5000; encode(&ctx, 2); assert(state.encodes == 1 && state.commits == 1 && state.cancels == 0); assert(ctx.metrics.encode_frames == 1 && ctx.metrics.sink_frames == 1); @@ -482,12 +489,14 @@ def structure(name): (uint32_t)(state.committed_meta.encode_start_timestamp_us - 90000)); assert(ctx.timing_window.idr_encode_count == 1 && ctx.timing_window.idr_encode_us[0] == 1000); assert(ctx.timing_window.p_encode_count == 0); - /* The totals since boot take the same frame: its type, its encode time - * and its handoff. */ + /* The totals since boot take the same frame: its type, its encode time, + * its handoff and its QP. */ assert(idr_frames_since_reset() == 1 && p_frames_since_reset() == 0); assert(s_video_encode_totals.idr_encode_us - totals_at_reset.idr_encode_us == 1000); assert(s_video_encode_totals.p_encode_us == totals_at_reset.p_encode_us); assert(s_video_encode_totals.handoff_us - totals_at_reset.handoff_us == 10000); + assert(s_video_encode_totals.qp_x100_sum - totals_at_reset.qp_x100_sum == 5000); + assert(s_video_encode_totals.coarse_frames - totals_at_reset.coarse_frames == 1); assert(state.complete_sync == 1 && state.last_completed_sync == 41); assert(state.last_completed_success && ctx.h264_sync_idr_generation == 0); assert(state.committed_meta.sequence == 1 && state.committed_meta.capture_sequence == 2); @@ -499,6 +508,7 @@ def structure(name): assert(state.committed_meta.width == 1920 && state.committed_meta.height == 1080); assert(state.committed_meta.fps == 30 && state.committed_meta.keyframe); assert(!state.committed_meta.encode_overlapped_capture); + state.frame_qp_x100 = 2850; encode(&ctx, 4); assert(state.commits == 2 && state.cancels == 0 && state.force_idr == 1); assert(!state.committed_meta.keyframe && state.committed_meta.sync_idr_generation == 0); @@ -507,6 +517,8 @@ def structure(name): assert(s_video_encode_totals.p_encode_us - totals_at_reset.p_encode_us == (uint64_t)(state.committed_meta.encode_done_timestamp_us - state.committed_meta.encode_start_timestamp_us)); + assert(s_video_encode_totals.qp_x100_sum - totals_at_reset.qp_x100_sum == 7850); + assert(s_video_encode_totals.coarse_frames - totals_at_reset.coarse_frames == 1); /* Encoder errors and empty output retire/requeue sync and restart the * reference chain. Failed output never reaches the consuming commit. */ @@ -515,9 +527,11 @@ def structure(name): ctx = reset(); state.pending_sync = 41; state.encode_result = failures[i]; + state.frame_qp_x100 = 5100; if (state.encode_result == ESP_H264_ERR_OK) state.encoded_length = 0; encode(&ctx, 2); assert(ctx.metrics.encode_overflows == (i < 2)); + assert(s_video_encode_totals.qp_x100_sum == totals_at_reset.qp_x100_sum); assert_recoverable_failure(&ctx); } @@ -560,7 +574,7 @@ def structure(name): assert(state.commits == 2 && state.cancels == 0 && !state.force_next_idr); if (pending) assert(state.last_completed_success && state.pending_sync == 0); } - puts("Encoder output leases: bitrate retune/retry, skip before IDR, DMA ownership, cancellation, reference recovery: PASS"); + puts("Encoder output leases: bitrate retune/retry, skip before IDR, DMA ownership, cancellation, reference recovery, frame QP: PASS"); } """ diff --git a/components/jetkvm_video/video_encode_totals.h b/components/jetkvm_video/video_encode_totals.h index 41f9f96b..d3eaa9ef 100644 --- a/components/jetkvm_video/video_encode_totals.h +++ b/components/jetkvm_video/video_encode_totals.h @@ -1,4 +1,4 @@ -/* Encode times of the hardware H.264 encoder since boot, for /webrtc/stats. +/* Encode times and QP of the hardware H.264 encoder since boot, for /webrtc/stats. * No lock and no clock of its own: the caller holds the lock of the video * metrics and gives the time. */ #pragma once @@ -13,6 +13,8 @@ * a full window without a frame, the next frame starts a new one. */ #define VIDEO_ENCODE_LONGEST_WINDOW_US (2 * 1000 * 1000) +#define VIDEO_ENCODE_COARSE_QP_X100 5000U + typedef struct { uint32_t p_encode_us; uint32_t idr_encode_us; @@ -26,16 +28,20 @@ typedef struct { uint64_t p_encode_us; uint64_t idr_encode_us; uint64_t handoff_us; + uint64_t qp_x100_sum; + uint32_t coarse_frames; int64_t window_end_us; video_encode_longest_t current; video_encode_longest_t previous; } video_encode_totals_t; -/* One encoded frame: now_us is the end of its encode. */ +/* One encoded frame: now_us is the end of its encode, qp_x100 its average + * QP in hundredths. */ static inline void video_encode_totals_add(video_encode_totals_t *totals, int64_t now_us, bool keyframe, uint32_t encode_us, - uint32_t handoff_us) + uint32_t handoff_us, + uint32_t qp_x100) { if (now_us >= totals->window_end_us) { if (now_us - totals->window_end_us < VIDEO_ENCODE_LONGEST_WINDOW_US) { @@ -64,6 +70,10 @@ static inline void video_encode_totals_add(video_encode_totals_t *totals, if (handoff_us > totals->current.handoff_us) { totals->current.handoff_us = handoff_us; } + totals->qp_x100_sum += qp_x100; + if (qp_x100 >= VIDEO_ENCODE_COARSE_QP_X100) { + totals->coarse_frames++; + } } /* The longest times a report at now_us has; zero for a kind of frame that diff --git a/components/jetkvm_video_quality/CMakeLists.txt b/components/jetkvm_video_quality/CMakeLists.txt index 129f65cb..66784b6a 100644 --- a/components/jetkvm_video_quality/CMakeLists.txt +++ b/components/jetkvm_video_quality/CMakeLists.txt @@ -1,5 +1,10 @@ +set(srcs "jetkvm_video_quality.c") +if(CONFIG_JETKVM_VIDEO_TUNING) + list(APPEND srcs "jetkvm_video_tuning.c") +endif() + idf_component_register( - SRCS "jetkvm_video_quality.c" + SRCS ${srcs} INCLUDE_DIRS "include") target_compile_options(${COMPONENT_LIB} PRIVATE -Werror) diff --git a/components/jetkvm_video_quality/Kconfig b/components/jetkvm_video_quality/Kconfig new file mode 100644 index 00000000..87be9c6a --- /dev/null +++ b/components/jetkvm_video_quality/Kconfig @@ -0,0 +1,17 @@ +menu "JetKVM video tuning" + +config JETKVM_VIDEO_TUNING + bool "Encoder toggles in /webrtc/stats (bench builds only)" + default n + help + Let GET /webrtc/stats?bitrate=1&qpMax=&rateKbps= set the + maximum QP and the rate target of the H.264 encoder, and give the + values in force in that answer (videoTuning). 0 is the firmware's + value. tools/sprites uses them to measure the picture. + + Bench builds set this option (the Dockerfile, with the + VIDEO_TUNING build argument that + tools/combined_load/runner/build.mjs gives). A release leaves it + off, and tools/release_config.py refuses a release build with it. + +endmenu diff --git a/components/jetkvm_video_quality/include/jetkvm_video_tuning.h b/components/jetkvm_video_quality/include/jetkvm_video_tuning.h new file mode 100644 index 00000000..19838f2b --- /dev/null +++ b/components/jetkvm_video_quality/include/jetkvm_video_tuning.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include + +#include "sdkconfig.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if CONFIG_JETKVM_VIDEO_TUNING + +/* Bench builds only. 0 keeps the firmware's value. */ +#define JETKVM_VIDEO_TUNING_QP_MAX 51U +#define JETKVM_VIDEO_TUNING_RATE_KBPS_MAX (UINT32_MAX / 1000U) + +/** False, and no change, when a value is above its maximum. */ +bool jetkvm_video_tuning_set(uint32_t qp_max, uint32_t rate_kbps); + +uint32_t jetkvm_video_tuning_qp_max(void); +uint32_t jetkvm_video_tuning_rate_kbps(void); + +#endif + +#ifdef __cplusplus +} +#endif diff --git a/components/jetkvm_video_quality/jetkvm_video_tuning.c b/components/jetkvm_video_quality/jetkvm_video_tuning.c new file mode 100644 index 00000000..91fc228d --- /dev/null +++ b/components/jetkvm_video_quality/jetkvm_video_tuning.c @@ -0,0 +1,25 @@ +#include "jetkvm_video_tuning.h" + +static uint32_t s_qp_max; +static uint32_t s_rate_kbps; + +bool jetkvm_video_tuning_set(uint32_t qp_max, uint32_t rate_kbps) +{ + if (qp_max > JETKVM_VIDEO_TUNING_QP_MAX || + rate_kbps > JETKVM_VIDEO_TUNING_RATE_KBPS_MAX) { + return false; + } + __atomic_store_n(&s_qp_max, qp_max, __ATOMIC_RELEASE); + __atomic_store_n(&s_rate_kbps, rate_kbps, __ATOMIC_RELEASE); + return true; +} + +uint32_t jetkvm_video_tuning_qp_max(void) +{ + return __atomic_load_n(&s_qp_max, __ATOMIC_ACQUIRE); +} + +uint32_t jetkvm_video_tuning_rate_kbps(void) +{ + return __atomic_load_n(&s_rate_kbps, __ATOMIC_ACQUIRE); +} diff --git a/components/webrtc_transport/include/webrtc_transport.h b/components/webrtc_transport/include/webrtc_transport.h index 608bd139..420d8d9d 100644 --- a/components/webrtc_transport/include/webrtc_transport.h +++ b/components/webrtc_transport/include/webrtc_transport.h @@ -766,6 +766,10 @@ typedef struct { /* Sum and longest over the P and IDR frames together. */ uint64_t handoff_us; uint32_t handoff_max_us; + /* Sum of each frame's average QP in hundredths, and the frames whose + * average QP is 50 or more. */ + uint64_t qp_x100_sum; + uint32_t coarse_frames; } webrtc_transport_video_encode_t; /** diff --git a/components/webrtc_transport/tests/test_stats_video_encode.py b/components/webrtc_transport/tests/test_stats_video_encode.py index 72d0c975..e3811114 100644 --- a/components/webrtc_transport/tests/test_stats_video_encode.py +++ b/components/webrtc_transport/tests/test_stats_video_encode.py @@ -99,6 +99,7 @@ def function(signature): .p_encode_max_us = 33490, .idr_frames = 7, .idr_encode_us = 192011, .idr_encode_max_us = 27743, .handoff_us = 4294967296ULL, .handoff_max_us = 14401, + .qp_x100_sum = 20400000000123ULL, .coarse_frames = 4000000000U, }; webrtc_transport_set_video_encode_source(source); json = render(); @@ -107,7 +108,8 @@ def function(signature): "{\"videoEncode\":{\"pFrames\":4000000000," "\"pEncodeUs\":131600000000123,\"pEncodeMaxUs\":33490," "\"idrFrames\":7,\"idrEncodeUs\":192011,\"idrEncodeMaxUs\":27743," - "\"handoffUs\":4294967296,\"handoffMaxUs\":14401}}") == 0); + "\"handoffUs\":4294967296,\"handoffMaxUs\":14401," + "\"qpX100Sum\":20400000000123,\"coarseFrames\":4000000000}}") == 0); free(json); /* Before the first frame the counters are there, at zero. */ @@ -116,7 +118,8 @@ def function(signature): assert(strcmp(json, "{\"videoEncode\":{\"pFrames\":0,\"pEncodeUs\":0,\"pEncodeMaxUs\":0," "\"idrFrames\":0,\"idrEncodeUs\":0,\"idrEncodeMaxUs\":0," - "\"handoffUs\":0,\"handoffMaxUs\":0}}") == 0); + "\"handoffUs\":0,\"handoffMaxUs\":0," + "\"qpX100Sum\":0,\"coarseFrames\":0}}") == 0); free(json); puts("videoEncode in /webrtc/stats: PASS"); return 0; diff --git a/components/webrtc_transport/webrtc_http.c b/components/webrtc_transport/webrtc_http.c index 03f968df..b2f000d5 100644 --- a/components/webrtc_transport/webrtc_http.c +++ b/components/webrtc_transport/webrtc_http.c @@ -36,6 +36,7 @@ #include "jetkvm_memory_policy.h" #include "jetkvm_timing_log.h" #include "jetkvm_usb_service.h" +#include "jetkvm_video_tuning.h" #include "playout_delay.h" #include "web_app.h" #include "webrtc_transport.h" @@ -615,6 +616,37 @@ static esp_err_t send_timing_log(httpd_req_t *req, char *json) return err; } +#if CONFIG_JETKVM_VIDEO_TUNING +/* ESP_OK and *value unchanged when the query has no such key. */ +static esp_err_t query_tuning_value(const char *query, const char *key, + uint32_t *value) +{ + char text[8]; + const esp_err_t error = httpd_query_key_value(query, key, text, sizeof(text)); + if (error == ESP_ERR_NOT_FOUND) { + return ESP_OK; + } + if (error != ESP_OK || text[0] == '\0' || + strspn(text, "0123456789") != strlen(text)) { + return ESP_ERR_INVALID_ARG; + } + *value = (uint32_t)strtoul(text, NULL, 10); + return ESP_OK; +} + +static esp_err_t apply_video_tuning(const char *query) +{ + uint32_t qp_max = jetkvm_video_tuning_qp_max(); + uint32_t rate_kbps = jetkvm_video_tuning_rate_kbps(); + if (query_tuning_value(query, "qpMax", &qp_max) != ESP_OK || + query_tuning_value(query, "rateKbps", &rate_kbps) != ESP_OK || + !jetkvm_video_tuning_set(qp_max, rate_kbps)) { + return ESP_ERR_INVALID_ARG; + } + return ESP_OK; +} +#endif + /* The stats the query asks for, printed; NULL with *error set when they * could not be built. */ static char *render_stats(const char *query, bool has_query, esp_err_t *error) @@ -626,6 +658,14 @@ static char *render_stats(const char *query, bool has_query, esp_err_t *error) bool bitrate = has_query && httpd_query_key_value(query, "bitrate", value, sizeof(value)) == ESP_OK && strcmp(value, "1") == 0; +#if CONFIG_JETKVM_VIDEO_TUNING + if (bitrate) { + *error = apply_video_tuning(query); + if (*error != ESP_OK) { + return NULL; + } + } +#endif cJSON *root = NULL; *error = bitrate ? webrtc_stats_json_create_bitrate(&root) : detailed ? webrtc_stats_json_create_detailed(&root) : @@ -659,6 +699,12 @@ static esp_err_t stats_handler(httpd_req_t *req) /* The configured priority, not the one read before: a task waiting on * the access guard's mutex may have lent this task its own. */ vTaskPrioritySet(NULL, JETKVM_HTTP_SERVER_TASK_PRIORITY); +#if CONFIG_JETKVM_VIDEO_TUNING + if (error == ESP_ERR_INVALID_ARG) { + return httpd_resp_send_err(req, HTTPD_400_BAD_REQUEST, + "qpMax or rateKbps is out of range"); + } +#endif if (error != ESP_OK) { const char *message = error == ESP_ERR_NO_MEM ? "no memory" : "stats unavailable"; diff --git a/components/webrtc_transport/webrtc_stats_json.c b/components/webrtc_transport/webrtc_stats_json.c index 1407c491..9be85da7 100644 --- a/components/webrtc_transport/webrtc_stats_json.c +++ b/components/webrtc_transport/webrtc_stats_json.c @@ -24,6 +24,7 @@ #include "jetkvm_memory_owners.h" #include "jetkvm_memory_policy.h" #include "jetkvm_usb_service.h" +#include "jetkvm_video_tuning.h" #include "jetkvm_virtual_media.h" #include "playout_delay.h" #include "webrtc_transport.h" @@ -201,6 +202,8 @@ static void add_video_encode(cJSON *root) cJSON_AddNumberToObject(object, "idrEncodeMaxUs", encode.idr_encode_max_us); add_u64(object, "handoffUs", encode.handoff_us); cJSON_AddNumberToObject(object, "handoffMaxUs", encode.handoff_max_us); + add_u64(object, "qpX100Sum", encode.qp_x100_sum); + cJSON_AddNumberToObject(object, "coarseFrames", encode.coarse_frames); cJSON_AddItemToObject(root, "videoEncode", object); } @@ -1811,6 +1814,13 @@ esp_err_t webrtc_stats_json_create_bitrate(cJSON **root_out) cJSON_AddNumberToObject(root, "psramMinimum", stats.psram_minimum); add_guest_video(root); add_video_encode(root); +#if CONFIG_JETKVM_VIDEO_TUNING + cJSON *tuning = cJSON_AddObjectToObject(root, "videoTuning"); + if (tuning) { + cJSON_AddNumberToObject(tuning, "qpMax", jetkvm_video_tuning_qp_max()); + cJSON_AddNumberToObject(tuning, "rateKbps", jetkvm_video_tuning_rate_kbps()); + } +#endif add_hdmi_receiver(root); add_audio(root); static const char *const phase_names[WEBRTC_PEER_PHASE_COUNT] = { diff --git a/docs/testing.md b/docs/testing.md index 11fbcb71..4feaa2bf 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -56,6 +56,16 @@ tools/combined_load/run.sh --list=full # full pairwise list Takes the Mini through the state lists in `tools/combined_load/lists.jsonc` (video, audio, virtual media, uploads, OS Services, cloud, an update, ...) and checks every second against each board's `criteria.jsonc`. See [tools/combined_load/README.md](../tools/combined_load/README.md). +## Picture under load + +```sh +node tools/sprites/sprites.mjs 1280x720@60 [qpMax] [rateKbps] +``` + +Measures the stream for 15 seconds while the host shows `tools/sprites/sprites.html` full screen: moving sprites beside static text, the same pictures on each run. Prints one JSON line (rate target, sent rate, frame rates, mean QP, share of frames at QP 50 or more) and writes a crop of the static text as PNG. Use it to compare encoder settings and firmware builds. + +The host must run Linux with GNOME and Chromium or Chrome, and accept an SSH key login; the tool sets its display mode and puts it back afterwards. The host must have one display in use, at a scale of 100 %; the tool refuses to change the mode of a host with more. The machine that runs the tool needs Chrome and `frontend/jetkvm-ui/node_modules`. `qpMax` (maximum QP) and `rateKbps` (rate target) override the encoder, 0 keeps the firmware's value. They need a bench build (`CONFIG_JETKVM_VIDEO_TUNING`, which `build.mjs` turns on); with a value other than 0, other firmware makes the tool stop with an error. + ## Recovering a Mini A Mini that won't boot or update can be written over its USB debugger: diff --git a/patches/esp_h264-1.4.1-frame-qp.patch b/patches/esp_h264-1.4.1-frame-qp.patch new file mode 100644 index 00000000..a7ecd8af --- /dev/null +++ b/patches/esp_h264-1.4.1-frame-qp.patch @@ -0,0 +1,133 @@ +diff --git a/managed_components/espressif__esp_h264/hw/include/esp_h264_enc_single_hw.h b/managed_components/espressif__esp_h264/hw/include/esp_h264_enc_single_hw.h +--- a/managed_components/espressif__esp_h264/hw/include/esp_h264_enc_single_hw.h ++++ b/managed_components/espressif__esp_h264/hw/include/esp_h264_enc_single_hw.h +@@ -36,6 +36,35 @@ + esp_h264_err_t esp_h264_enc_hw_new(const esp_h264_enc_cfg_hw_t *cfg, esp_h264_enc_handle_t *out_enc); + + /** ++ * @brief Average QP of the last frame that the encoder coded ++ * ++ * @note Call it from the task that calls `esp_h264_enc_process`. A frame ++ * that did not fit the output buffer does not change the value. ++ * ++ * @param[in] enc The encoder instance that is from `esp_h264_enc_hw_new` ++ * @param[out] out_qp_x100 The QP sum over the frame's macroblocks times 100, ++ * divided by the macroblock count; 0 before the first frame ++ * ++ * @return ++ * - ESP_H264_ERR_OK Succeeded ++ * - ESP_H264_ERR_ARG Invalid arguments passed ++ */ ++esp_h264_err_t esp_h264_enc_hw_get_frame_qp_x100(esp_h264_enc_handle_t enc, uint32_t *out_qp_x100); ++ ++/** ++ * @brief Change the QP range of rate control from the next frame on ++ * ++ * @param[in] enc The encoder instance that is from `esp_h264_enc_hw_new` ++ * @param[in] qp_min Minimum QP, at most `qp_max` ++ * @param[in] qp_max Maximum QP, at most ESP_H264_QP_MAX ++ * ++ * @return ++ * - ESP_H264_ERR_OK Succeeded ++ * - ESP_H264_ERR_ARG Invalid arguments passed, or the encoder has no rate control ++ */ ++esp_h264_err_t esp_h264_enc_hw_set_qp_range(esp_h264_enc_handle_t enc, uint8_t qp_min, uint8_t qp_max); ++ ++/** + * @brief This function returns a pointer to the hardware-encoded parameter structure associated with the given `esp_h264_enc_t` encoder + * + * @param[in] enc The encoder instance that is from `esp_h264_enc_hw_new` +diff --git a/managed_components/espressif__esp_h264/hw/src/esp_h264_enc_single_hw.c b/managed_components/espressif__esp_h264/hw/src/esp_h264_enc_single_hw.c +--- a/managed_components/espressif__esp_h264/hw/src/esp_h264_enc_single_hw.c ++++ b/managed_components/espressif__esp_h264/hw/src/esp_h264_enc_single_hw.c +@@ -527,3 +527,34 @@ + } + return ESP_H264_ERR_ARG; + } ++ ++esp_h264_err_t esp_h264_enc_hw_get_frame_qp_x100(esp_h264_enc_handle_t enc, uint32_t *out_qp_x100) ++{ ++ if (enc == NULL || out_qp_x100 == NULL) { ++ return ESP_H264_ERR_ARG; ++ } ++ esp_h264_hw_handle_t *hw_hd = __containerof(enc, esp_h264_hw_handle_t, base); ++ esp_h264_rc_hd_t rc_hd = NULL; ++ esp_h264_enc_hw_get_rc_hd(hw_hd->param_hd, &rc_hd); ++ *out_qp_x100 = esp_h264_rc_frame_qp_x100(rc_hd); ++ return ESP_H264_ERR_OK; ++} ++ ++esp_h264_err_t esp_h264_enc_hw_set_qp_range(esp_h264_enc_handle_t enc, uint8_t qp_min, uint8_t qp_max) ++{ ++ if (enc == NULL || qp_min > qp_max || qp_max > ESP_H264_QP_MAX) { ++ return ESP_H264_ERR_ARG; ++ } ++ esp_h264_hw_handle_t *hw_hd = __containerof(enc, esp_h264_hw_handle_t, base); ++ esp_h264_rc_hd_t rc_hd = NULL; ++ esp_h264_enc_hw_get_rc_hd(hw_hd->param_hd, &rc_hd); ++ if (rc_hd == NULL) { ++ return ESP_H264_ERR_ARG; ++ } ++ esp_h264_mutex_t mutex; ++ esp_h264_enc_hw_get_mutex(hw_hd->param_hd, &mutex); ++ esp_h264_mutex_lock(mutex, ESP_H264_MAX_DELAY); ++ esp_h264_enc_hw_rc_set_qp(rc_hd, qp_max, qp_min); ++ esp_h264_mutex_unlock(mutex); ++ return ESP_H264_ERR_OK; ++} +diff --git a/managed_components/espressif__esp_h264/hw/src/h264_rc.c b/managed_components/espressif__esp_h264/hw/src/h264_rc.c +--- a/managed_components/espressif__esp_h264/hw/src/h264_rc.c ++++ b/managed_components/espressif__esp_h264/hw/src/h264_rc.c +@@ -15,6 +15,7 @@ + int8_t qpm; + int8_t eqp; + uint8_t qp_average_frame; ++ uint32_t qp_sum_last; /* QP sum over the macroblocks of the last frame that reached esp_h264_rc_end() */ + uint32_t target_frame_bits; + uint32_t bits_per_frame; + uint32_t frame_bits_last[4]; +@@ -41,6 +42,15 @@ + } + } + ++uint32_t esp_h264_rc_frame_qp_x100(esp_h264_rc_hd_t rc_hd) ++{ ++ esp_h264_rc_t *prc = (esp_h264_rc_t *)rc_hd; ++ if (prc == NULL || prc->mb_cnt == 0) { ++ return 0; ++ } ++ return (uint32_t)(((uint64_t)prc->qp_sum_last * 100U + prc->mb_cnt / 2U) / prc->mb_cnt); ++} ++ + esp_h264_rc_hd_t esp_h264_enc_hw_rc_new(uint8_t qp_max, uint8_t qp_min, uint32_t bitrate, uint8_t fps, uint8_t mb_width, uint8_t mb_height) + { + uint32_t actual_size; +@@ -161,6 +171,7 @@ + + mad_cur = 1.0f * frame_mad_sum / prc->mb_cnt; + prc->qp_average_frame = frame_qp_sum / prc->mb_cnt; ++ prc->qp_sum_last = frame_qp_sum; + frame_err = (int64_t)total_enc_bits - (int64_t)prc->bits_per_frame; + prc->ebits = CLIP3(-prc->ebits_sat_clip, prc->ebits_sat_clip, prc->ebits + frame_err); + +diff --git a/managed_components/espressif__esp_h264/hw/src/h264_rc.h b/managed_components/espressif__esp_h264/hw/src/h264_rc.h +--- a/managed_components/espressif__esp_h264/hw/src/h264_rc.h ++++ b/managed_components/espressif__esp_h264/hw/src/h264_rc.h +@@ -72,6 +72,17 @@ + void esp_h264_rc_end(esp_h264_rc_hd_t rc_hd, uint32_t total_enc_bits, uint32_t frame_qp_sum, uint32_t frame_mad_sum); + + /** ++ * @brief Average QP of the last frame that reached esp_h264_rc_end() ++ * ++ * @param rc_hd Rate control handle ++ * ++ * @return The frame's QP sum over its macroblocks times 100, divided by the ++ * macroblock count and rounded; 0 without a handle or before the ++ * first frame ++ */ ++uint32_t esp_h264_rc_frame_qp_x100(esp_h264_rc_hd_t rc_hd); ++ ++/** + * @brief Delete RC handle + * + * @param rc_hd Rate control handle diff --git a/patches/tests/test_h264_frame_qp_patch.py b/patches/tests/test_h264_frame_qp_patch.py new file mode 100644 index 00000000..6d8ab063 --- /dev/null +++ b/patches/tests/test_h264_frame_qp_patch.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""The frame-QP patch applies after the other esp_h264 patches, and a second +configure finds every esp_h264 patch applied. + +git apply reverse-checks each patch on the patched component, so a later +patch must leave the context lines of the earlier ones as they are. +""" +from pathlib import Path +import shutil +import subprocess +import tempfile + +ROOT = Path(__file__).resolve().parents[2] +COMPONENT = Path("managed_components/espressif__esp_h264") +PATCH = "patches/esp_h264-1.4.1-frame-qp.patch" + +cmake = (ROOT / "CMakeLists.txt").read_text() +start = cmake.index("apply_managed_component_patch(patches/esp_h264-") +end = cmake.index(f"apply_managed_component_patch({PATCH})") +region = cmake[start:end] + f"apply_managed_component_patch({PATCH})\n" +assert "apply_managed_component_patch(patches/esp_h264-1.4.1-overflow-qp.patch)" in region +patches = sorted({line.split("(")[1].rstrip(")") for line in region.splitlines() + if line.startswith("apply_managed_component_patch(")}) + +with tempfile.TemporaryDirectory(prefix="h264-frame-qp-") as directory: + work = Path(directory) + subprocess.run(["git", "init", "-q", str(work)], check=True) + shutil.copytree(ROOT / COMPONENT, work / COMPONENT) + shutil.copytree(ROOT / "patches", work / "patches") + script = work / "configure.cmake" + script.write_text( + f'set(CMAKE_SOURCE_DIR "{work}")\n' + f'include("{ROOT}/cmake/apply_managed_component_patch.cmake")\n' + region + ) + for attempt in range(2): + result = subprocess.run(["cmake", "-P", str(script)], cwd=work, + capture_output=True, text=True) + output = result.stdout + result.stderr + assert result.returncode == 0, output + for patch in patches: + assert f"Managed-component patch already applied: {patch}" in output, (patch, output) + + header = (work / COMPONENT / "hw/include/esp_h264_enc_single_hw.h").read_text() + for declaration in ( + "esp_h264_err_t esp_h264_enc_hw_get_frame_qp_x100(esp_h264_enc_handle_t enc, uint32_t *out_qp_x100);", + "esp_h264_err_t esp_h264_enc_hw_set_qp_range(esp_h264_enc_handle_t enc, uint8_t qp_min, uint8_t qp_max);", + ): + assert declaration in header, declaration +print("H264 frame QP patch: applies after the other esp_h264 patches, and a second configure: PASS") diff --git a/tools/combined_load/runner/build.mjs b/tools/combined_load/runner/build.mjs index 73560735..94d83cfc 100644 --- a/tools/combined_load/runner/build.mjs +++ b/tools/combined_load/runner/build.mjs @@ -48,6 +48,7 @@ export function benchBuildArguments(bench, plainCloud, usbDebugging = true) { MOCK_CLOUD_JWKS_URL: plainCloud ? keys : keys.replace(/^http:/, 'https:'), USB_DEBUGGING: usbDebugging ? '1' : '0', MEMORY_OWNERS: '1', + VIDEO_TUNING: '1', }; } diff --git a/tools/combined_load/runner/combined_load.test.mjs b/tools/combined_load/runner/combined_load.test.mjs index 2c5b5b12..9322bb40 100644 --- a/tools/combined_load/runner/combined_load.test.mjs +++ b/tools/combined_load/runner/combined_load.test.mjs @@ -5585,11 +5585,11 @@ test('on both boards a slow key is a glitch: a key over 150 ms once a window is test('the build has the bench file\'s board, setup code and cloud key URL, USB debugging on and the memory count per task on', () => { const ethernet = { JETKVM_SKU: 'jetkvm-mini-ethernet', JETKVM_MOCK_CLOUD_JWKS_URL: 'http://192.168.1.102:8791/oidc/jwks' }; assert.deepEqual(benchBuildArguments(ethernet, false), - { BOARD: 'ethernet', WIFI_SETUP_LOG_CODE: '0', MOCK_CLOUD_JWKS_URL: 'https://192.168.1.102:8791/oidc/jwks', USB_DEBUGGING: '1', MEMORY_OWNERS: '1' }); + { BOARD: 'ethernet', WIFI_SETUP_LOG_CODE: '0', MOCK_CLOUD_JWKS_URL: 'https://192.168.1.102:8791/oidc/jwks', USB_DEBUGGING: '1', MEMORY_OWNERS: '1', VIDEO_TUNING: '1' }); assert.equal(benchBuildArguments(ethernet, true).MOCK_CLOUD_JWKS_URL, 'http://192.168.1.102:8791/oidc/jwks'); assert.equal(benchBuildArguments(ethernet, false, false).USB_DEBUGGING, '0'); assert.deepEqual(benchBuildArguments({ JETKVM_SKU: 'jetkvm-mini-wireless', JETKVM_WIFI_SSID: 'bench' }, false), - { BOARD: 'wifi', WIFI_SETUP_LOG_CODE: '1', MOCK_CLOUD_JWKS_URL: '', USB_DEBUGGING: '1', MEMORY_OWNERS: '1' }); + { BOARD: 'wifi', WIFI_SETUP_LOG_CODE: '1', MOCK_CLOUD_JWKS_URL: '', USB_DEBUGGING: '1', MEMORY_OWNERS: '1', VIDEO_TUNING: '1' }); assert.throws(() => benchBuildArguments({ JETKVM_SKU: 'jetkvm' }, false), /JETKVM_SKU "jetkvm"/); }); diff --git a/tools/release_config.py b/tools/release_config.py index 42e10acb..8b8c17a2 100644 --- a/tools/release_config.py +++ b/tools/release_config.py @@ -23,6 +23,7 @@ "JETKVM_VIRTUAL_MEDIA_HTTP_DIAGNOSTIC_DISCARD": True, "JETKVM_USB_DEBUGGING_DEFAULT_ON": True, "JETKVM_MEMORY_OWNERS": True, + "JETKVM_VIDEO_TUNING": True, "JETKVM_BENCH_CUSTOM_MAC": True, } diff --git a/tools/sprites/host.sh b/tools/sprites/host.sh new file mode 100755 index 00000000..b14e3c03 --- /dev/null +++ b/tools/sprites/host.sh @@ -0,0 +1,56 @@ +#!/bin/sh +# Runs on the rig host (GNOME), beside sprites.html. sprites.mjs copies and calls it. +# host.sh mode [ ] print " ", then set a mode +# host.sh show show the page full screen +# host.sh count the page's "n= frames= late= size=" line +# host.sh close +set -e +export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/$(id -u)}" +export DBUS_SESSION_BUS_ADDRESS="${DBUS_SESSION_BUS_ADDRESS:-unix:path=$XDG_RUNTIME_DIR/bus}" +eval "$(systemctl --user show-environment | grep -E '^(WAYLAND_DISPLAY|DISPLAY|XAUTHORITY|XDG_SESSION_TYPE)=' | sed 's/^/export /')" +dir=$(cd "$(dirname "$0")" && pwd) +unit=jetkvm-sprites +close() { systemctl --user stop $unit 2>/dev/null || true; systemctl --user reset-failed $unit 2>/dev/null || true; } +case "$1" in +mode) + shift + python3 - "$@" <<'EOF' +import sys +from gi.repository import Gio, GLib +bus = Gio.bus_get_sync(Gio.BusType.SESSION, None) +call = lambda method, arguments: bus.call_sync( + "org.gnome.Mutter.DisplayConfig", "/org/gnome/Mutter/DisplayConfig", + "org.gnome.Mutter.DisplayConfig", method, arguments, None, Gio.DBusCallFlags.NONE, -1, None) +serial, monitors, logicals, _ = call("GetCurrentState", None).unpack() +x, y, scale, transform, primary, assigned, _l = logicals[0] +connector = assigned[0][0] +modes = next(m for m in monitors if m[0][0] == connector)[1] +current = next(m for m in modes if m[6].get("is-current")) +print(current[1], current[2], round(current[3])) +if len(sys.argv) > 3: + in_use = [(c[0], logical[2]) for logical in logicals for c in logical[5]] + if len(in_use) != 1 or in_use[0][1] != 1.0: + sys.exit("a mode change needs one display in use, at a scale of 100 %; this host has " + + ", ".join("%s at %d %%" % (name, round(scale * 100)) for name, scale in in_use)) + wanted, rate = (int(sys.argv[1]), int(sys.argv[2])), float(sys.argv[3]) + fit = sorted((m for m in modes if (m[1], m[2]) == wanted), key=lambda m: abs(m[3] - rate)) + if not fit: + sys.exit("%s offers no %dx%d" % ((connector,) + wanted)) + if not fit[0][6].get("is-current"): + call("ApplyMonitorsConfig", GLib.Variant("(uua(iiduba(ssa{sv}))a{sv})", + (serial, 1, [(x, y, scale, transform, primary, [(connector, fit[0][0], {})])], {}))) +EOF + ;; +show) + close + rm -rf "$dir/profile" + gdbus call --session --dest org.gnome.ScreenSaver --object-path /org/gnome/ScreenSaver \ + --method org.gnome.ScreenSaver.SetActive false >/dev/null 2>&1 || true + systemd-run --user --quiet --collect --unit=$unit \ + gnome-session-inhibit --inhibit idle --reason "JetKVM sprites" \ + "$(command -v google-chrome || command -v chromium)" --kiosk "file://$dir/sprites.html?n=$2&hz=$3" \ + --remote-debugging-port=9222 --no-first-run --no-default-browser-check --password-store=basic \ + --disable-features=Translate --test-type --user-data-dir="$dir/profile" ;; +count) curl -s http://127.0.0.1:9222/json | grep -o 'n=[0-9]* frames=[0-9]* late=[0-9]* size=[0-9x]*' | head -1 ;; +close) close ;; +esac diff --git a/tools/sprites/sprites.html b/tools/sprites/sprites.html new file mode 100644 index 00000000..a2b9e171 --- /dev/null +++ b/tools/sprites/sprites.html @@ -0,0 +1,81 @@ + + +sprites + + + +
+ diff --git a/tools/sprites/sprites.mjs b/tools/sprites/sprites.mjs new file mode 100644 index 00000000..091c4068 --- /dev/null +++ b/tools/sprites/sprites.mjs @@ -0,0 +1,126 @@ +#!/usr/bin/env node +// One measurement of the Mini's picture under a sprite load. +// +// node tools/sprites/sprites.mjs [qpMax] [rateKbps] +// +// mode is the host's display mode, as 1280x720@60. sprites is the load. +// qpMax and rateKbps are the encoder toggles of a bench build +// (CONFIG_JETKVM_VIDEO_TUNING); 0 is the firmware's value. Prints one JSON +// line and writes text----.png: the static +// text beside the sprites, at the stream's own pixels. SPRITES_FRAME=1 also +// writes the full frame. +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import { createRequire } from "node:module"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const require = createRequire(path.join(here, "..", "..", "frontend", "jetkvm-ui", "node_modules") + path.sep); +const { chromium } = require("playwright-core"); + +const args = process.argv.slice(2); +const [MINI, HOST, mode, sprites, qpMax = "0", rateKbps = "0"] = args; +const size = mode?.match(/^(\d+)x(\d+)@(\d+)$/)?.slice(1); +if (args.length < 4 || args.length > 6 || !URL.canParse(MINI) || !HOST || !size || + ![sprites, qpMax, rateKbps].every(value => /^\d+$/.test(value)) || Number(qpMax) > 51) { + console.error("usage: sprites.mjs x@ [qpMax 0-51] [rateKbps]"); + process.exit(2); +} +const [width, height, hz] = size.map(Number); +const tuning = { qpMax: Number(qpMax), rateKbps: Number(rateKbps) }; +const SECONDS = 15; +const SSH = ["-o", "BatchMode=yes"]; + +const host = (...args) => + execFileSync("ssh", [...SSH, HOST, "jetkvm-sprites/host.sh", ...args], { encoding: "utf8" }).trim(); +const hostCount = () => { + const m = host("count").match(/frames=(\d+) late=(\d+) size=(\S+)/); + if (m?.[3] !== `${width}x${height}`) throw new Error(`the page does not fill the ${mode} screen: "${m?.[0] ?? "not started"}"`); + return { frames: Number(m[1]), late: Number(m[2]) }; +}; +const mini = async (query = "") => { + const response = await fetch(new URL(`/webrtc/stats?bitrate=1${query}`, MINI)); + if (!response.ok) throw new Error(`/webrtc/stats${query}: ${response.status} ${await response.text()}`); + return response.json(); +}; +const setTuning = async wanted => { + const active = (await mini(`&qpMax=${wanted.qpMax}&rateKbps=${wanted.rateKbps}`)).videoTuning; + if (active?.qpMax !== wanted.qpMax || active?.rateKbps !== wanted.rateKbps) { + throw new Error(`the Mini reports videoTuning ${JSON.stringify(active)} after it was set to ${JSON.stringify(wanted)}`); + } +}; + +const found = await mini(); +if (typeof found.videoEncode?.qpX100Sum !== "number") { + throw new Error("the Mini's firmware has no QP counters in videoEncode"); +} +const tunable = "videoTuning" in found; +if (!tunable && (tuning.qpMax || tuning.rateKbps)) { + throw new Error("the Mini's firmware has no encoder toggles: build it with CONFIG_JETKVM_VIDEO_TUNING (a bench build)"); +} +execFileSync("ssh", [...SSH, HOST, "mkdir -p jetkvm-sprites"]); +execFileSync("scp", ["-q", ...SSH, path.join(here, "host.sh"), path.join(here, "sprites.html"), `${HOST}:jetkvm-sprites/`]); +const modeFound = host("mode", ...size); +let browser; +try { + if (tunable) await setTuning(tuning); + for (let i = 0; host("mode") !== size.join(" "); i++) { + if (i === 20) throw new Error(`the host did not change to ${mode}`); + await new Promise(r => setTimeout(r, 500)); + } + host("show", sprites, String(hz)); + browser = await chromium.launch({ headless: true, channel: "chrome" }); + const page = await browser.newPage(); + await page.goto(MINI, { waitUntil: "domcontentloaded" }); + await page.waitForFunction( + () => window.__kvmTestHooks?.isWebRTCConnected?.() && window.__kvmTestHooks?.isVideoStreamActive?.(), + null, { timeout: 60000 }); + await page.waitForTimeout(8000); + const browserStats = () => page.evaluate(() => window.__kvmTestHooks.getInboundVideoStats()); + const quality = await page.evaluate(() => new Promise(resolve => + window.__kvmTestHooks.sendJsonRpc("getStreamQualityFactor", {}, r => resolve(r.result ?? r.error?.message)))); + const a = { mini: await mini(), browser: await browserStats(), host: hostCount() }; + await page.waitForTimeout(SECONDS * 1000); + const b = { mini: await mini(), browser: await browserStats(), host: hostCount() }; + const [text, frame] = await page.evaluate(([w, h]) => Promise.all([ + window.__kvmTestHooks.captureVideoRegion(0, 0, 250, 450), + w && window.__kvmTestHooks.captureVideoRegion(0, 0, w, h)]), [process.env.SPRITES_FRAME ? width : 0, height]); + fs.writeFileSync(`text-${mode}-${sprites}-${qpMax}-${rateKbps}.png`, Buffer.from(text.split(",")[1], "base64")); + if (frame) fs.writeFileSync(`frame-${mode}-${sprites}-${qpMax}-${rateKbps}.png`, Buffer.from(frame.split(",")[1], "base64")); + + const seconds = (b.browser.timestamp - a.browser.timestamp) / 1000; + const encoded = k => b.mini.videoEncode[k] - a.mini.videoEncode[k]; + const hostFrames = b.host.frames - a.host.frames, hostLate = b.host.late - a.host.late; + const frames = encoded("pFrames") + encoded("idrFrames"); + console.log(JSON.stringify({ + mode, sprites: Number(sprites), ...tuning, + targetKbps: Math.round(b.mini.videoTargetBitrate / 1000), + sentKbps: Math.round((b.browser.bytesReceived - a.browser.bytesReceived) * 8 / seconds / 1000), + encodedFps: +(frames / seconds).toFixed(1), + shownFps: +((b.browser.framesDecoded - a.browser.framesDecoded) / seconds).toFixed(1), + slotDrops: b.mini.accessUnitsNoSlot - a.mini.accessUnitsNoSlot, + freezes: b.browser.freezeCount - a.browser.freezeCount, + meanQp: +(encoded("qpX100Sum") / 100 / frames).toFixed(1), + coarseShare: +(encoded("coarseFrames") / frames).toFixed(2), + quality, lossPermille: b.mini.videoBitrateLossPermille, reason: b.mini.videoBitrateReason, + // The page counts frames in steps of 30. + valid: hostLate * 100 <= hostFrames && hostFrames / seconds > hz * 0.93 && + b.mini.width === width && b.mini.height === height && b.mini.fps === hz, + hostLate, + })); +} finally { + for (const step of [ + () => browser?.close(), + () => tunable && setTuning({ qpMax: 0, rateKbps: 0 }), + () => host("close"), + () => host("mode", ...modeFound.split(" ")), + ]) { + try { + await step(); + } catch (e) { + console.error(`cleanup: ${e.message}`); + process.exitCode = 1; + } + } +}