Merge remote-tracking branch 'upstream/master'

This commit is contained in:
Vindicus999
2025-11-03 01:53:00 +00:00
36 changed files with 1000 additions and 488 deletions
+1 -1
View File
@@ -49,7 +49,7 @@ systemctl enable --now avahi-daemon
- On your headset, run WiVRn from the App Library. If you are using a Quest and you have installed it from an APK instead of the Meta Store, it will be in the "unknown sources" section. - On your headset, run WiVRn from the App Library. If you are using a Quest and you have installed it from an APK instead of the Meta Store, it will be in the "unknown sources" section.
- You should now see your computer in the list: click connect, the screen will show "Connection ready. Start a VR application on **your computer's name**". - You should now see your computer in the list: click connect, the screen will show "Connection ready. Start a VR application on **your computer's name**".
You can now start an OpenXR application on your computer. For Steam games, you will also need to set the launch options to be able to use WiVRn: You can now start an OpenXR application on your computer. For Steam games, you may also need to set the launch options to be able to use WiVRn. If nothing related to Steam is displayed in the dashboard or wivrn-server output, then your system does not require it.
- Right-click on the game you want to play in VR in Steam and click "Properties". - Right-click on the game you want to play in VR in Steam and click "Properties".
- In the "General" tab, set the launch options to the value given in the dashboard. - In the "General" tab, set the launch options to the value given in the dashboard.
+11 -2
View File
@@ -18,6 +18,7 @@
#pragma once #pragma once
#include <array>
#include <cstdint> #include <cstdint>
#include <glm/glm.hpp> #include <glm/glm.hpp>
#include <imgui.h> #include <imgui.h>
@@ -68,7 +69,14 @@ constexpr uint32_t pointer_color_border = 0xff000000;
namespace constants::lobby namespace constants::lobby
{ {
// Position and orientation of the GUI layers // Position and orientation of the GUI layers
constexpr float gui_pitch = -0.2; constexpr auto gui_pitches = std::to_array<std::pair<float, float>>({
{-90, -90},
{-50, -90},
{-30, -12},
{30, -12},
{50, 78},
{90, 78},
});
constexpr float keyboard_pitch = -0.6; constexpr float keyboard_pitch = -0.6;
constexpr glm::vec3 popup_position = {0, 0, 0.05}; constexpr glm::vec3 popup_position = {0, 0, 0.05};
constexpr glm::vec3 keyboard_position = {0, -0.3, 0.1}; constexpr glm::vec3 keyboard_position = {0, -0.3, 0.1};
@@ -77,7 +85,8 @@ constexpr glm::vec3 keyboard_position = {0, -0.3, 0.1};
constexpr float near_plane = 0.02; constexpr float near_plane = 0.02;
// Recenter gesture thresholds // Recenter gesture thresholds
constexpr float recenter_cosangle_min = 0.8; constexpr float recenter_cos_palm_angle_min = 0.7;
constexpr float recenter_cos_fingertip_angle_max = 0.3;
constexpr float recenter_distance_up = 0.3; constexpr float recenter_distance_up = 0.3;
constexpr float recenter_distance_front = 0.2; constexpr float recenter_distance_front = 0.2;
+91 -27
View File
@@ -31,6 +31,7 @@
#include "render/scene_components.h" #include "render/scene_components.h"
#include "stream.h" #include "stream.h"
#include "utils/files.h" #include "utils/files.h"
#include "utils/glm_cast.h"
#include "utils/i18n.h" #include "utils/i18n.h"
#include "wivrn_client.h" #include "wivrn_client.h"
#include "wivrn_discover.h" #include "wivrn_discover.h"
@@ -84,14 +85,38 @@ static const std::array supported_depth_formats{
vk::Format::eX8D24UnormPack32, vk::Format::eX8D24UnormPack32,
}; };
static float interpolate(float x, std::span<const std::pair<float, float>> arr)
{
assert(arr.size() >= 1);
if (x <= arr[0].first)
return arr[0].second;
if (x >= arr.back().first)
return arr.back().second;
for (size_t i = 0; i + 1 < arr.size(); i++)
{
assert(arr[i].first <= arr[i + 1].first);
if (arr[i].first <= x and x < arr[i + 1].first)
{
auto t = (x - arr[i].first) / (arr[i + 1].first - arr[i].first);
return std::lerp(arr[i].second, arr[i + 1].second, t);
}
}
return arr[0].second; // Should never happen
}
static glm::quat compute_gui_orientation(glm::vec3 head_position, glm::vec3 new_gui_position) static glm::quat compute_gui_orientation(glm::vec3 head_position, glm::vec3 new_gui_position)
{ {
using constants::lobby::gui_pitch;
glm::vec3 gui_direction = new_gui_position - head_position; glm::vec3 gui_direction = new_gui_position - head_position;
float gui_yaw = atan2(gui_direction.x, gui_direction.z) + M_PI; float gui_yaw = atan2(gui_direction.x, gui_direction.z) + M_PI;
float eye_gaze_elevation = atan2(gui_direction.y, glm::length(glm::vec2(gui_direction.x, gui_direction.z)));
float gui_pitch = interpolate(eye_gaze_elevation * 180 / M_PI, constants::lobby::gui_pitches) * M_PI / 180;
return glm::quat(cos(gui_yaw / 2), 0, sin(gui_yaw / 2), 0) * glm::quat(cos(gui_pitch / 2), sin(gui_pitch / 2), 0, 0); return glm::quat(cos(gui_yaw / 2), 0, sin(gui_yaw / 2), 0) * glm::quat(cos(gui_pitch / 2), sin(gui_pitch / 2), 0, 0);
} }
@@ -403,27 +428,59 @@ void scenes::lobby::connect(const configuration::server_data & data)
data.manual); data.manual);
} }
std::optional<glm::vec3> scenes::lobby::check_recenter_gesture(xr::spaces space, const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints) std::optional<glm::vec3> scenes::lobby::check_recenter_gesture(
xr::spaces space,
const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints,
const std::pair<glm::vec3, glm::quat> & head_pose)
{ {
if (recentering_context and std::get<0>(*recentering_context) != space) if (recentering_context and std::get<0>(*recentering_context) != space)
return std::nullopt; return std::nullopt;
if (not joints) if (joints)
{ {
recentering_context.reset(); const auto & palm = (*joints)[XR_HAND_JOINT_PALM_EXT].first;
return std::nullopt; const auto palm_y = glm::rotate(glm_cast(palm.pose.orientation), glm::vec3(0, 1, 0));
}
const auto & palm = (*joints)[XR_HAND_JOINT_PALM_EXT].first; for (XrHandJointEXT index: {
const auto & o = palm.pose.orientation; XR_HAND_JOINT_INDEX_PROXIMAL_EXT,
const auto & p = palm.pose.position; XR_HAND_JOINT_INDEX_INTERMEDIATE_EXT,
glm::quat q{o.w, o.x, o.y, o.z}; XR_HAND_JOINT_INDEX_DISTAL_EXT,
glm::vec3 v{p.x, p.y, p.z};
if (glm::dot(q * glm::vec3(0, 1, 0), glm::vec3(0, -1, 0)) > constants::lobby::recenter_cosangle_min) XR_HAND_JOINT_MIDDLE_PROXIMAL_EXT,
{ XR_HAND_JOINT_MIDDLE_INTERMEDIATE_EXT,
recentering_context.emplace(space, glm::vec3{}, 0); XR_HAND_JOINT_MIDDLE_DISTAL_EXT,
return v + glm::vec3(0, constants::lobby::recenter_distance_up, 0) + q * glm::vec3(0, 0, -constants::lobby::recenter_distance_front);
XR_HAND_JOINT_RING_PROXIMAL_EXT,
XR_HAND_JOINT_RING_INTERMEDIATE_EXT,
XR_HAND_JOINT_RING_DISTAL_EXT,
XR_HAND_JOINT_LITTLE_PROXIMAL_EXT,
XR_HAND_JOINT_LITTLE_INTERMEDIATE_EXT,
XR_HAND_JOINT_LITTLE_DISTAL_EXT,
})
{
const auto fingertip_y = glm::rotate(glm_cast((*joints)[index].first.pose.orientation), glm::vec3(0, 1, 0));
if (glm::dot(palm_y, fingertip_y) < constants::lobby::recenter_cos_fingertip_angle_max)
{
recentering_context.reset();
return std::nullopt;
}
}
const auto q = glm_cast(palm.pose.orientation);
const auto x = glm_cast(palm.pose.position);
// Make the up vector orthogonal to forward
const glm::vec3 forward = glm::rotate(head_pose.second, glm::vec3{0, 0, -1});
const glm::vec3 up = glm::normalize(glm::vec3{0, 1, 0} - forward * glm::dot(forward, {0, 1, 0}));
// Y is pointing to the back of the hand
if (glm::dot(q * glm::vec3(0, -1, 0), up) > constants::lobby::recenter_cos_palm_angle_min)
{
recentering_context.emplace(space, glm::vec3{}, 0);
return x + glm::rotate(q, glm::vec3{0, -constants::lobby::recenter_distance_up, -constants::lobby::recenter_distance_front});
}
} }
recentering_context.reset(); recentering_context.reset();
@@ -535,14 +592,21 @@ std::optional<glm::vec3> scenes::lobby::check_recenter_action(XrTime predicted_d
// One step is usually enough, the solution will continuously improve in the next frames // One step is usually enough, the solution will continuously improve in the next frames
glm::vec3 gui_position = imgui_ctx->layers()[0].position; glm::vec3 gui_position = imgui_ctx->layers()[0].position;
float eps = 0.01; float eps = 0.01;
glm::vec3 obj = f(gui_position);
glm::vec3 obj_dx = (f(gui_position + glm::vec3(eps, 0, 0)) - obj) / eps;
glm::vec3 obj_dy = (f(gui_position + glm::vec3(0, eps, 0)) - obj) / eps;
glm::vec3 obj_dz = (f(gui_position + glm::vec3(0, 0, eps)) - obj) / eps;
glm::mat3 jacobian{obj_dx, obj_dy, obj_dz}; glm::vec3 obj;
int n_iter = 0;
do
{
obj = f(gui_position);
glm::vec3 obj_dx = (f(gui_position + glm::vec3(eps, 0, 0)) - obj) / eps;
glm::vec3 obj_dy = (f(gui_position + glm::vec3(0, eps, 0)) - obj) / eps;
glm::vec3 obj_dz = (f(gui_position + glm::vec3(0, 0, eps)) - obj) / eps;
gui_position -= glm::inverse(jacobian) * obj; glm::mat3 jacobian{obj_dx, obj_dy, obj_dz};
gui_position -= 0.01 * glm::inverse(jacobian) * obj;
n_iter++;
} while (glm::length(obj) > 0.0001 and n_iter < 1000);
return gui_position; return gui_position;
} }
@@ -928,14 +992,14 @@ void scenes::lobby::render(const XrFrameState & frame_state)
hand_model::apply(world, left, right); hand_model::apply(world, left, right);
if (not new_gui_position) if (not new_gui_position and head_position)
new_gui_position = check_recenter_gesture(xr::spaces::palm_left, left); new_gui_position = check_recenter_gesture(xr::spaces::palm_left, left, *head_position);
if (not new_gui_position) if (not new_gui_position and head_position)
new_gui_position = check_recenter_gesture(xr::spaces::palm_right, right); new_gui_position = check_recenter_gesture(xr::spaces::palm_right, right, *head_position);
} }
if (head_position && new_gui_position) if (head_position and new_gui_position)
{ {
move_gui(head_position->first, *new_gui_position); move_gui(head_position->first, *new_gui_position);
} }
+1 -1
View File
@@ -238,7 +238,7 @@ class lobby : public scene_impl<lobby>
void connect(const configuration::server_data & data); void connect(const configuration::server_data & data);
std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service service, bool manual_connection); std::unique_ptr<wivrn_session> connect_to_session(wivrn_discover::service service, bool manual_connection);
std::optional<glm::vec3> check_recenter_gesture(xr::spaces space, const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints); std::optional<glm::vec3> check_recenter_gesture(xr::spaces space, const std::optional<std::array<xr::hand_tracker::joint, XR_HAND_JOINT_COUNT_EXT>> & joints, const std::pair<glm::vec3, glm::quat> & head_pose);
std::optional<glm::vec3> check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position); std::optional<glm::vec3> check_recenter_action(XrTime predicted_display_time, glm::vec3 head_position);
std::optional<glm::vec3> check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation); std::optional<glm::vec3> check_recenter_gui(glm::vec3 head_position, glm::quat head_orientation);
+4
View File
@@ -304,6 +304,10 @@ std::shared_ptr<scenes::stream> scenes::stream::create(std::unique_ptr<wivrn_ses
return info; return info;
}()); }());
self->network_session->send_control(from_headset::session_state_changed{
.state = application::get_session_state(),
});
if (self->instance.has_extension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME)) if (self->instance.has_extension(XR_KHR_VISIBILITY_MASK_EXTENSION_NAME))
{ {
for (uint8_t view = 0; view < view_count; ++view) for (uint8_t view = 0; view < view_count; ++view)
+7
View File
@@ -626,7 +626,14 @@ void scenes::stream::gui_applications()
auto btn = _("Start"); auto btn = _("Start");
ImGui::SetCursorPos(ImGui::GetWindowSize() - ImGui::CalcTextSize(btn.c_str()) - ImVec2(50, 50)); ImGui::SetCursorPos(ImGui::GetWindowSize() - ImGui::CalcTextSize(btn.c_str()) - ImVec2(50, 50));
if (ImGui::Button(btn.c_str())) if (ImGui::Button(btn.c_str()))
{
network_session->send_control(from_headset::get_application_list{
.language = application::get_messages_info().language,
.country = application::get_messages_info().country,
.variant = application::get_messages_info().variant,
});
gui_status = gui_status::application_launcher; gui_status = gui_status::application_launcher;
}
imgui_ctx->vibrate_on_hover(); imgui_ctx->vibrate_on_hover();
ImGui::PopStyleVar(3); ImGui::PopStyleVar(3);
} }
+42
View File
@@ -0,0 +1,42 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Guillaume Meunier <guillaume.meunier@centraliens.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include <glm/gtc/quaternion.hpp>
#include <openxr/openxr.h>
inline glm::quat glm_cast(const XrQuaternionf & q)
{
return glm::quat::wxyz(q.w, q.x, q.y, q.z);
}
inline XrQuaternionf glm_cast(const glm::quat & q)
{
return XrQuaternionf(q.w, q.x, q.y, q.z);
}
inline glm::vec3 glm_cast(const XrVector3f & v)
{
return glm::vec3(v.x, v.y, v.z);
}
inline XrVector3f glm_cast(const glm::vec3 & v)
{
return XrVector3f(v.x, v.y, v.z);
}
+5 -1
View File
@@ -27,11 +27,16 @@ target_sources(wivrn-dashboard PRIVATE ${DBUS_INTERFACE_SRC})
set_source_files_properties(../images/wivrn.svg PROPERTIES QT_RESOURCE_ALIAS qml/wivrn.svg) set_source_files_properties(../images/wivrn.svg PROPERTIES QT_RESOURCE_ALIAS qml/wivrn.svg)
set_source_files_properties(qml/DashboardSettings.qml PROPERTIES
QT_QML_SINGLETON_TYPE TRUE
)
qt_add_qml_module(wivrn-dashboard qt_add_qml_module(wivrn-dashboard
URI io.github.wivrn.wivrn URI io.github.wivrn.wivrn
QML_FILES QML_FILES
qml/Main.qml qml/Main.qml
qml/ApkInstallPage.qml qml/ApkInstallPage.qml
qml/DashboardSettings.qml
qml/SettingsPage.qml qml/SettingsPage.qml
qml/HeadsetsPage.qml qml/HeadsetsPage.qml
qml/HeadsetStatsPage.qml qml/HeadsetStatsPage.qml
@@ -50,7 +55,6 @@ qt_add_qml_module(wivrn-dashboard
qml/Github.svg qml/Github.svg
) )
configure_file(gui_config.h.in gui_config.h) configure_file(gui_config.h.in gui_config.h)
configure_file(io.github.wivrn.wivrn.desktop.in io.github.wivrn.wivrn.desktop) configure_file(io.github.wivrn.wivrn.desktop.in io.github.wivrn.wivrn.desktop)
+13
View File
@@ -0,0 +1,13 @@
pragma Singleton
import QtCore
Settings {
property bool first_run: true
property bool show_system_checks: true
property string last_run_version: ""
property bool adb_custom: false
property string adb_location: ""
}
+8 -17
View File
@@ -42,15 +42,6 @@ Kirigami.ApplicationWindow {
onClosing: Qt.quit() onClosing: Qt.quit()
Core.Settings {
id: settings
property alias first_run: root.first_run
property alias last_run_version: root.last_run_version
property bool show_system_checks: true
}
property bool first_run: true
property string last_run_version
width: 900 width: 900
height: 800 height: 800
@@ -76,10 +67,10 @@ Kirigami.ApplicationWindow {
if (value == WivrnServer.FailedToStart) if (value == WivrnServer.FailedToStart)
message_failed_to_start.visible = true; message_failed_to_start.visible = true;
if (root.first_run && started) { if (DashboardSettings.first_run && started) {
console.log("First run"); console.log("First run");
root.pageStack.push(Qt.createComponent("WizardPage.qml").createObject()); root.pageStack.push(Qt.createComponent("WizardPage.qml").createObject());
root.first_run = false; DashboardSettings.first_run = false;
} }
} }
@@ -109,8 +100,8 @@ Kirigami.ApplicationWindow {
if (WivrnServer.serverStatus == WivrnServer.Stopped) if (WivrnServer.serverStatus == WivrnServer.Stopped)
WivrnServer.start_server(); WivrnServer.start_server();
if (root.last_run_version != ApkInstaller.currentVersion) { if (DashboardSettings.last_run_version != ApkInstaller.currentVersion) {
root.last_run_version = ApkInstaller.currentVersion; DashboardSettings.last_run_version = ApkInstaller.currentVersion;
} }
} }
@@ -130,7 +121,7 @@ Kirigami.ApplicationWindow {
text: i18n("Avahi daemon is not installed") text: i18n("Avahi daemon is not installed")
type: Kirigami.MessageType.Warning type: Kirigami.MessageType.Warning
showCloseButton: true showCloseButton: true
visible: settings.show_system_checks && !Avahi.installed visible: DashboardSettings.show_system_checks && !Avahi.installed
} }
Kirigami.InlineMessage { Kirigami.InlineMessage {
@@ -138,7 +129,7 @@ Kirigami.ApplicationWindow {
text: i18n("Avahi daemon is not started") text: i18n("Avahi daemon is not started")
type: Kirigami.MessageType.Warning type: Kirigami.MessageType.Warning
showCloseButton: true showCloseButton: true
visible: settings.show_system_checks && Avahi.installed && !Avahi.running visible: DashboardSettings.show_system_checks && Avahi.installed && !Avahi.running
actions: [ actions: [
Kirigami.Action { Kirigami.Action {
visible: Avahi.canStart visible: Avahi.canStart
@@ -154,7 +145,7 @@ Kirigami.ApplicationWindow {
// type: Kirigami.MessageType.Warning // type: Kirigami.MessageType.Warning
type: Kirigami.MessageType.Information type: Kirigami.MessageType.Information
showCloseButton: true showCloseButton: true
visible: settings.show_system_checks && !WivrnServer.capSysNice visible: DashboardSettings.show_system_checks && !WivrnServer.capSysNice
actions: [ actions: [
Kirigami.Action { Kirigami.Action {
text: i18n("Fix it") text: i18n("Fix it")
@@ -168,7 +159,7 @@ Kirigami.ApplicationWindow {
text: i18n("Firewall may not allow port 9757") text: i18n("Firewall may not allow port 9757")
type: Kirigami.MessageType.Warning type: Kirigami.MessageType.Warning
showCloseButton: true showCloseButton: true
visible: settings.show_system_checks && Firewall.needSetup visible: DashboardSettings.show_system_checks && Firewall.needSetup
actions: [ actions: [
Kirigami.Action { Kirigami.Action {
text: i18n("Fix it") text: i18n("Fix it")
+19 -17
View File
@@ -15,18 +15,12 @@ Kirigami.ScrollablePage {
flickable.interactive: false // Make sure the Kirigami.ScrollablePage does not eat the vertical mouse dragging events flickable.interactive: false // Make sure the Kirigami.ScrollablePage does not eat the vertical mouse dragging events
property bool allowUpdates: false // ignore onXXX events until document is loaded
Settings { Settings {
id: config id: config
} }
Core.Settings {
property alias adb_custom: settings.adb_custom
property alias adb_location: settings.adb_location
property alias show_system_checks: show_system_checks.checked
}
property bool adb_custom
property string adb_location
ColumnLayout { ColumnLayout {
id: column id: column
anchors.fill: parent anchors.fill: parent
@@ -96,7 +90,6 @@ Kirigami.ScrollablePage {
Kirigami.FormData.label: i18n("Bitrate:") Kirigami.FormData.label: i18n("Bitrate:")
from: 1 from: 1
to: 200 to: 200
value: config.bitrate
textFromValue: (value, locale) => i18nc("bitrate", "%1 Mbit/s", value) textFromValue: (value, locale) => i18nc("bitrate", "%1 Mbit/s", value)
valueFromText: function (text, locale) { valueFromText: function (text, locale) {
@@ -150,7 +143,7 @@ Kirigami.ScrollablePage {
encoder: Settings.X264 encoder: Settings.X264
} }
] ]
onCurrentIndexChanged: config.encoder = model[currentIndex].encoder onCurrentIndexChanged: if (settings.allowUpdates) {config.encoder = model[currentIndex].encoder}
textRole: "label" textRole: "label"
Connections { Connections {
target: config target: config
@@ -190,7 +183,7 @@ Kirigami.ScrollablePage {
codec: Settings.Av1 codec: Settings.Av1
} }
] ]
onCurrentIndexChanged: config.codec = model[currentIndex].codec onCurrentIndexChanged: if (settings.allowUpdates) {config.codec = model[currentIndex].codec}
textRole: "label" textRole: "label"
delegate: Controls.ItemDelegate { delegate: Controls.ItemDelegate {
@@ -216,6 +209,7 @@ Kirigami.ScrollablePage {
enabled: config.can10bit enabled: config.can10bit
text: i18n("10-bits") text: i18n("10-bits")
checked: config.tenbit checked: config.tenbit
onCheckedChanged: config.tenbit = checked
} }
Kirigami.ContextualHelpButton { Kirigami.ContextualHelpButton {
toolTipText: i18n("10-bit encoding improves image quality but is not supported by all codecs and hardware") toolTipText: i18n("10-bit encoding improves image quality but is not supported by all codecs and hardware")
@@ -272,7 +266,7 @@ Kirigami.ScrollablePage {
enabled: adb_custom.checked enabled: adb_custom.checked
Controls.TextField { Controls.TextField {
id: adb_location id: adb_location
placeholderText: settings.adb_location placeholderText: DashboardSettings.adb_location
Layout.fillWidth: true Layout.fillWidth: true
} }
Controls.Button { Controls.Button {
@@ -372,6 +366,10 @@ Kirigami.ScrollablePage {
Component.onCompleted: { Component.onCompleted: {
openvr_libs.init() openvr_libs.init()
config.load(WivrnServer); config.load(WivrnServer);
// If bitrate was manually set higher, keep the limit
bitrate.to = Math.max(bitrate.to, config.bitrate)
bitrate.value = config.bitrate
settings.allowUpdates = true;
settings.load(); settings.load();
} }
@@ -383,9 +381,11 @@ Kirigami.ScrollablePage {
} else { } else {
config.openvr = openvr.value config.openvr = openvr.value
} }
settings.adb_custom = adb_custom.checked; DashboardSettings.adb_custom = adb_custom.checked;
settings.adb_location = adb_location.text; DashboardSettings.adb_location = adb_location.text;
Adb.setPath(adb_custom.checked ? adb_location.text : "adb"); Adb.setPath(DashboardSettings.adb_custom.checked ? adb_location.text : "adb");
DashboardSettings.show_system_checks = show_system_checks.checked;
config.debugGui = debug_gui.checked; config.debugGui = debug_gui.checked;
config.steamVrLh = steamvr_lh.checked; config.steamVrLh = steamvr_lh.checked;
@@ -403,8 +403,10 @@ Kirigami.ScrollablePage {
openvr_combobox.load() openvr_combobox.load()
adb_custom.checked = settings.adb_custom; adb_custom.checked = DashboardSettings.adb_custom;
adb_location.text = settings.adb_location; adb_location.text = DashboardSettings.adb_location;
show_system_checks.checked = DashboardSettings.show_system_checks;
} }
Shortcut { Shortcut {
+12 -3
View File
@@ -206,6 +206,7 @@ Settings::encoder_name Settings::encoder() const
void Settings::set_encoder(const encoder_name & value) void Settings::set_encoder(const encoder_name & value)
{ {
auto old = encoder(); auto old = encoder();
auto old_codec = codec();
switch (value) switch (value)
{ {
case EncoderAuto: case EncoderAuto:
@@ -237,10 +238,11 @@ void Settings::set_encoder(const encoder_name & value)
if (value != old) if (value != old)
{ {
encoderChanged(); encoderChanged();
codecChanged();
if (not can10bit()) if (not can10bit())
set_tenbit(false); set_tenbit(false);
} }
if (old_codec != codec())
codecChanged();
simpleConfigChanged(); simpleConfigChanged();
} }
@@ -468,9 +470,16 @@ QList<Settings::video_codec> Settings::allowedCodecs() const
video_codec::H265, video_codec::H265,
video_codec::Av1, video_codec::Av1,
}; };
case encoder_name::X264:
case encoder_name::Vulkan: case encoder_name::Vulkan:
return {video_codec::H264}; return {
video_codec::CodecAuto,
video_codec::H264,
video_codec::H265,
};
case encoder_name::X264:
return {
video_codec::H264,
};
} }
return {video_codec::CodecAuto}; return {video_codec::CodecAuto};
} }
+1
View File
@@ -10,6 +10,7 @@ It also requires at least one encoder:
* For nvenc (Nvidia), it requires cuda and nvidia driver * For nvenc (Nvidia), it requires cuda and nvidia driver
* For vaapi (AMD/Intel), it requires ffmpeg with vaapi and libdrm support, as well as vaapi drivers for the GPU * For vaapi (AMD/Intel), it requires ffmpeg with vaapi and libdrm support, as well as vaapi drivers for the GPU
* For vulkan (Any modern GPU), it requires vulkan headers of 1.3.283 or later, as well as vulkan drivers for the GPU
* For x264 (software encoding), it requires libx264 * For x264 (software encoding), it requires libx264
Some distributions such as Fedora don't ship h264 and h265 encoders and need specific repositories. Some distributions such as Fedora don't ship h264 and h265 encoders and need specific repositories.
+6 -1
View File
@@ -64,7 +64,12 @@ Identifier of the encoder, one of
Default value: first supported by both headset and encoder of `av1`, `h264`, `h265`. Default value: first supported by both headset and encoder of `av1`, `h264`, `h265`.
One of `h264`, `h265`, `av1`, `raw`. One of `h264`, `h265`, `av1`, `raw`.
Not all encoders support every codec, `x264` and `vulkan` only support `h264`. For `raw` codec, only `raw` encoder can be used.
Not all encoders support every codec:
- `x264` encoder only supports `h264` codec
- `vulkan` encoder supports `h264` and `h265` codecs
- `raw` encoder only supports `raw` codec
- `nvenc` and `vaapi` support all codecs, except `raw`
If `nvenc` encoder is in use, you can refer to [nvidia website](https://developer.nvidia.com/video-encode-decode-support-matrix) to make sure that your GPU supports encoding with the desired codec. If `nvenc` encoder is in use, you can refer to [nvidia website](https://developer.nvidia.com/video-encode-decode-support-matrix) to make sure that your GPU supports encoding with the desired codec.
+2 -1
View File
@@ -87,6 +87,7 @@ if (WIVRN_BUILD_SERVER)
audio/audio_setup.cpp audio/audio_setup.cpp
encoder/encoder_settings.cpp encoder/encoder_settings.cpp
encoder/idr_handler.cpp
encoder/video_encoder.cpp encoder/video_encoder.cpp
encoder/video_encoder_raw.cpp encoder/video_encoder_raw.cpp
@@ -152,7 +153,7 @@ if (WIVRN_BUILD_SERVER)
target_sources(wivrn-server PRIVATE target_sources(wivrn-server PRIVATE
encoder/video_encoder_vulkan.cpp encoder/video_encoder_vulkan.cpp
encoder/video_encoder_vulkan_h264.cpp encoder/video_encoder_vulkan_h264.cpp
#encoder/video_encoder_vulkan_h265.cpp encoder/video_encoder_vulkan_h265.cpp
) )
endif() endif()
+2 -2
View File
@@ -819,14 +819,14 @@ static void comp_wivrn_info_gpu(struct comp_target * ct, int64_t frame_id, int64
void wivrn_comp_target::on_feedback(const from_headset::feedback & feedback, const clock_offset & o) void wivrn_comp_target::on_feedback(const from_headset::feedback & feedback, const clock_offset & o)
{ {
if (not o)
return;
uint8_t stream = feedback.stream_index; uint8_t stream = feedback.stream_index;
if (psc.status & 1) if (psc.status & 1)
return; return;
if (encoders.size() <= stream) if (encoders.size() <= stream)
return; return;
encoders[stream]->on_feedback(feedback); encoders[stream]->on_feedback(feedback);
if (not o)
return;
pacer.on_feedback(feedback, o); pacer.on_feedback(feedback, o);
} }
+7 -2
View File
@@ -16,8 +16,8 @@
* You should have received a copy of the GNU General Public License * You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include "encoder_settings.h" #include "encoder_settings.h"
#include "driver/configuration.h" #include "driver/configuration.h"
#include "util/u_logging.h" #include "util/u_logging.h"
#include "utils/wivrn_vk_bundle.h" #include "utils/wivrn_vk_bundle.h"
@@ -289,7 +289,12 @@ static void fill_defaults(wivrn_vk_bundle & bundle, const std::vector<wivrn::vid
#endif #endif
if (config.name == encoder_vulkan and not config.codec) if (config.name == encoder_vulkan and not config.codec)
config.codec = h264; // this will fail if 10-bit is enabled {
if (bit_depth == 10)
config.codec = h265;
else
config.codec = h264;
}
#if WIVRN_USE_X264 #if WIVRN_USE_X264
if (config.name == encoder_x264) if (config.name == encoder_x264)
@@ -18,8 +18,8 @@
*/ */
#include "video_encoder_ffmpeg.h" #include "video_encoder_ffmpeg.h"
#include "util/u_logging.h" #include "util/u_logging.h"
#include <stdexcept>
extern "C" extern "C"
{ {
@@ -66,21 +66,24 @@ namespace wivrn
bool video_encoder_ffmpeg::once = set_log_level(); bool video_encoder_ffmpeg::once = set_log_level();
std::optional<wivrn::video_encoder::data> video_encoder_ffmpeg::encode(bool idr, std::chrono::steady_clock::time_point target_timestamp, uint8_t slot) std::optional<wivrn::video_encoder::data> video_encoder_ffmpeg::encode(uint8_t slot, uint64_t frame_index)
{ {
auto & idr_handler = (default_idr_handler &)*idr;
if (auto bitrate = pending_bitrate.exchange(0)) if (auto bitrate = pending_bitrate.exchange(0))
{ {
idr = true; idr_handler.reset();
encoder_ctx->bit_rate = bitrate; encoder_ctx->bit_rate = bitrate;
encoder_ctx->rc_max_rate = bitrate; encoder_ctx->rc_max_rate = bitrate;
} }
if (auto framerate = pending_framerate.exchange(0)) if (auto framerate = pending_framerate.exchange(0))
{ {
idr = true; idr_handler.reset();
encoder_ctx->framerate = AVRational{.num = int(framerate * 1000), .den = 1000}; encoder_ctx->framerate = AVRational{.num = int(framerate * 1000), .den = 1000};
} }
push_frame(idr, target_timestamp, slot); bool is_idr = idr_handler.get_type(frame_index) == default_idr_handler::frame_type::i;
push_frame(is_idr, slot);
std::shared_ptr<AVPacket> enc_pkt(av_packet_alloc(), [](AVPacket * d) { av_packet_free(&d); }); std::shared_ptr<AVPacket> enc_pkt(av_packet_alloc(), [](AVPacket * d) { av_packet_free(&d); });
int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get()); int err = avcodec_receive_packet(encoder_ctx.get(), enc_pkt.get());
if (err == 0) if (err == 0)
@@ -89,6 +92,7 @@ std::optional<wivrn::video_encoder::data> video_encoder_ffmpeg::encode(bool idr,
.encoder = this, .encoder = this,
.span = std::span(enc_pkt->data, enc_pkt->size), .span = std::span(enc_pkt->data, enc_pkt->size),
.mem = std::move(enc_pkt), // elements are evaluated in order .mem = std::move(enc_pkt), // elements are evaluated in order
.prefer_control = is_idr,
}; };
} }
if (err == AVERROR(EAGAIN)) if (err == AVERROR(EAGAIN))
+3 -4
View File
@@ -21,7 +21,6 @@
#include "encoder/video_encoder.h" #include "encoder/video_encoder.h"
#include "ffmpeg_helper.h" #include "ffmpeg_helper.h"
#include <chrono>
namespace wivrn namespace wivrn
{ {
@@ -29,7 +28,7 @@ namespace wivrn
class video_encoder_ffmpeg : public wivrn::video_encoder class video_encoder_ffmpeg : public wivrn::video_encoder
{ {
public: public:
std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point target_timestamp, uint8_t slot) override; std::optional<data> encode(uint8_t slot, uint64_t frame_index) override;
struct mute_logs struct mute_logs
{ {
@@ -39,9 +38,9 @@ public:
protected: protected:
video_encoder_ffmpeg(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, double bitrate_multiplier) : video_encoder_ffmpeg(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, double bitrate_multiplier) :
wivrn::video_encoder(stream_idx, channels, bitrate_multiplier, true) {} wivrn::video_encoder(stream_idx, channels, std::make_unique<default_idr_handler>(), bitrate_multiplier, true) {}
virtual void push_frame(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) = 0; virtual void push_frame(bool idr, uint8_t slot) = 0;
av_codec_context_ptr encoder_ctx; av_codec_context_ptr encoder_ctx;
+1 -2
View File
@@ -526,11 +526,10 @@ std::pair<bool, vk::Semaphore> video_encoder_va::present_image(vk::Image y_cbcr,
return {false, nullptr}; return {false, nullptr};
} }
void video_encoder_va::push_frame(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) void video_encoder_va::push_frame(bool idr, uint8_t slot)
{ {
auto & va_frame = in[slot].va_frame; auto & va_frame = in[slot].va_frame;
va_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P; va_frame->pict_type = idr ? AV_PICTURE_TYPE_I : AV_PICTURE_TYPE_P;
va_frame->pts = pts.time_since_epoch().count();
int err = avcodec_send_frame(encoder_ctx.get(), va_frame.get()); int err = avcodec_send_frame(encoder_ctx.get(), va_frame.get());
if (err) if (err)
{ {
+1 -2
View File
@@ -23,7 +23,6 @@
#include "video_encoder_ffmpeg.h" #include "video_encoder_ffmpeg.h"
#include <array> #include <array>
#include <chrono>
#include <vector> #include <vector>
#include <vulkan/vulkan_raii.hpp> #include <vulkan/vulkan_raii.hpp>
@@ -53,6 +52,6 @@ public:
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
protected: protected:
void push_frame(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) override; void push_frame(bool idr, uint8_t slot) override;
}; };
} // namespace wivrn } // namespace wivrn
+87
View File
@@ -0,0 +1,87 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "idr_handler.h"
#include "utils/overloaded.h"
namespace wivrn
{
idr_handler::~idr_handler() = default;
void default_idr_handler::on_feedback(const from_headset::feedback & f)
{
std::unique_lock lock(mutex);
std::visit(utils::overloaded{
[](need_idr) {},
[](idr_received) {},
[this, &f](wait_idr_feedback s) {
if (f.sent_to_decoder and f.frame_index == s.idr_id)
state = idr_received{};
},
[this, &f](running r) {
if (not f.sent_to_decoder and f.frame_index >= r.first_p)
state = need_idr{};
},
},
state);
}
void default_idr_handler::reset()
{
std::unique_lock lock(mutex);
state = need_idr{};
}
bool default_idr_handler::should_skip(uint64_t frame_id)
{
std::unique_lock lock(mutex);
return std::visit(utils::overloaded{
[this, frame_id](wait_idr_feedback w) {
if (frame_id > w.idr_id + 100)
{
state = need_idr{};
return false;
}
return true;
},
[](auto) {
return false;
},
},
state);
}
default_idr_handler::frame_type default_idr_handler::get_type(uint64_t frame_index)
{
std::unique_lock lock(mutex);
return std::visit(utils::overloaded{
[](need_idr) {
return frame_type::i;
},
[this, frame_index](idr_received) {
state = running{frame_index};
return frame_type::p;
},
[](auto) {
return frame_type::p;
},
},
state);
}
} // namespace wivrn
+71
View File
@@ -0,0 +1,71 @@
/*
* WiVRn VR streaming
* Copyright (C) 2025 Patrick Nicolas <patricknicolas@laposte.net>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#pragma once
#include "wivrn_packets.h"
#include <cstdint>
#include <mutex>
#include <variant>
namespace wivrn
{
class idr_handler
{
public:
virtual ~idr_handler();
virtual void on_feedback(const from_headset::feedback &) = 0;
virtual void reset() = 0;
virtual bool should_skip(uint64_t frame_id) = 0;
};
// handler for unknown P-frames
// any lost frame triggers an I-frame
// skip frames until th I frame is received
class default_idr_handler : public idr_handler
{
std::mutex mutex;
struct need_idr
{};
struct wait_idr_feedback
{
uint64_t idr_id;
};
struct idr_received
{};
struct running
{
uint64_t first_p;
};
std::variant<need_idr, wait_idr_feedback, idr_received, running> state;
public:
enum class frame_type
{
i,
p,
};
void on_feedback(const from_headset::feedback &) override;
void reset() override;
bool should_skip(uint64_t frame_id) override;
frame_type get_type(uint64_t frame_index);
};
} // namespace wivrn
+45 -49
View File
@@ -24,7 +24,6 @@
#include "encoder_settings.h" #include "encoder_settings.h"
#include "os/os_time.h" #include "os/os_time.h"
#include "util/u_logging.h"
#include "wivrn_config.h" #include "wivrn_config.h"
#include <string> #include <string>
@@ -40,7 +39,7 @@
#endif #endif
#if WIVRN_USE_VULKAN_ENCODE #if WIVRN_USE_VULKAN_ENCODE
#include "video_encoder_vulkan_h264.h" #include "video_encoder_vulkan_h264.h"
// #include "video_encoder_vulkan_h265.h" #include "video_encoder_vulkan_h265.h"
#endif #endif
#include "video_encoder_raw.h" #include "video_encoder_raw.h"
@@ -122,9 +121,8 @@ std::unique_ptr<video_encoder> video_encoder::create(
res = video_encoder_vulkan_h264::create(wivrn_vk, settings, fps, stream_idx); res = video_encoder_vulkan_h264::create(wivrn_vk, settings, fps, stream_idx);
break; break;
case video_codec::h265: case video_codec::h265:
throw std::runtime_error("h265 not supported for vulkan video encode"); res = video_encoder_vulkan_h265::create(wivrn_vk, settings, fps, stream_idx);
// res = video_encoder_vulkan_h265::create(wivrn_vk, settings, fps); break;
// break;
case video_codec::av1: case video_codec::av1:
throw std::runtime_error("av1 not supported for vulkan video encode"); throw std::runtime_error("av1 not supported for vulkan video encode");
case video_codec::raw: case video_codec::raw:
@@ -192,15 +190,15 @@ std::unique_ptr<video_encoder> video_encoder::create(
return res; return res;
} }
static const uint64_t idr_throttle = 100; video_encoder::video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, std::unique_ptr<idr_handler> idr, double bitrate_multiplier, bool async_send) :
video_encoder::video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, double bitrate_multiplier, bool async_send) :
stream_idx(stream_idx), stream_idx(stream_idx),
channels(channels), channels(channels),
bitrate_multiplier(bitrate_multiplier), bitrate_multiplier(bitrate_multiplier),
last_idr_frame(-idr_throttle), shared_sender(async_send ? sender::get() : nullptr),
shared_sender(async_send ? sender::get() : nullptr) idr(std::move(idr))
{} {
assert(idr);
}
video_encoder::~video_encoder() video_encoder::~video_encoder()
{ {
@@ -210,13 +208,13 @@ video_encoder::~video_encoder()
void video_encoder::on_feedback(const from_headset::feedback & feedback) void video_encoder::on_feedback(const from_headset::feedback & feedback)
{ {
if (not feedback.sent_to_decoder) assert(feedback.stream_index == stream_idx);
sync_needed = true; idr->on_feedback(feedback);
} }
void video_encoder::reset() void video_encoder::reset()
{ {
sync_needed = true; idr->reset();
} }
void video_encoder::set_bitrate(int bitrate_bps) void video_encoder::set_bitrate(int bitrate_bps)
@@ -233,13 +231,20 @@ std::pair<bool, vk::Semaphore> video_encoder::present_image(vk::Image y_cbcr, vk
{ {
// Wait for encoder to be done // Wait for encoder to be done
present_slot = (present_slot + 1) % num_slots; present_slot = (present_slot + 1) % num_slots;
busy[present_slot].wait(true); state[present_slot].wait(busy);
busy[present_slot] = true; if (idr->should_skip(frame_index))
{
state[present_slot] = skip;
return {false, nullptr};
}
state[present_slot] = busy;
return present_image(y_cbcr, cmd_buf, present_slot, frame_index); return present_image(y_cbcr, cmd_buf, present_slot, frame_index);
} }
void video_encoder::post_submit() void video_encoder::post_submit()
{ {
if (state[present_slot] == skip)
return;
post_submit(present_slot); post_submit(present_slot);
} }
@@ -248,28 +253,30 @@ void video_encoder::encode(wivrn_session & cnx,
uint64_t frame_index) uint64_t frame_index)
{ {
encode_slot = (encode_slot + 1) % num_slots; encode_slot = (encode_slot + 1) % num_slots;
assert(busy[encode_slot].load());
struct idle_setter
{
std::atomic_unsigned_lock_free & state;
~idle_setter()
{
state = idle;
state.notify_all();
}
};
idle_setter i{state[encode_slot]};
if (state[encode_slot] == skip)
return;
if (shared_sender) if (shared_sender)
shared_sender->wait_idle(this); shared_sender->wait_idle(this);
this->cnx = &cnx; this->cnx = &cnx;
auto target_timestamp = std::chrono::steady_clock::time_point(std::chrono::nanoseconds(view_info.display_time));
bool idr = sync_needed.exchange(false);
// Throttle idr to prevent overloading the decoder
if (idr and frame_index < last_idr_frame + idr_throttle)
{
U_LOG_D("Throttle IDR: stream %" PRIu8 " frame %" PRIu64, stream_idx, frame_index);
sync_needed = true;
idr = false;
}
if (idr)
last_idr_frame = frame_index;
const char * extra = idr ? ",idr" : ",p";
clock = cnx.get_offset(); clock = cnx.get_offset();
auto encode_begin = os_monotonic_get_ns();
timing_info = { timing_info = {
.encode_begin = clock.to_headset(os_monotonic_get_ns()), .encode_begin = clock.to_headset(encode_begin),
}; };
cnx.dump_time("encode_begin", frame_index, os_monotonic_get_ns(), stream_idx, extra);
// Prepare the video shard template // Prepare the video shard template
shard.stream_item_idx = stream_idx; shard.stream_item_idx = stream_idx;
@@ -278,26 +285,15 @@ void video_encoder::encode(wivrn_session & cnx,
shard.view_info = view_info; shard.view_info = view_info;
shard.timing_info.reset(); shard.timing_info.reset();
std::exception_ptr ex; auto data = encode(encode_slot, frame_index);
try cnx.dump_time("encode_begin", frame_index, encode_begin, stream_idx);
cnx.dump_time("encode_end", frame_index, os_monotonic_get_ns(), stream_idx);
if (data)
{ {
auto data = encode(idr, target_timestamp, encode_slot); timing_info.encode_end = clock.to_headset(os_monotonic_get_ns());
cnx.dump_time("encode_end", frame_index, os_monotonic_get_ns(), stream_idx, extra); assert(shared_sender);
if (data) shared_sender->push(std::move(*data));
{
timing_info.encode_end = clock.to_headset(os_monotonic_get_ns());
assert(shared_sender);
shared_sender->push(std::move(*data));
}
} }
catch (...)
{
ex = std::current_exception();
}
busy[encode_slot] = false;
busy[encode_slot].notify_all();
if (ex)
std::rethrow_exception(ex);
} }
void video_encoder::SendData(std::span<uint8_t> data, bool end_of_frame, bool control) void video_encoder::SendData(std::span<uint8_t> data, bool end_of_frame, bool control)
+14 -10
View File
@@ -20,10 +20,10 @@
#pragma once #pragma once
#include "driver/clock_offset.h" #include "driver/clock_offset.h"
#include "idr_handler.h"
#include "wivrn_packets.h" #include "wivrn_packets.h"
#include <atomic> #include <atomic>
#include <chrono>
#include <condition_variable> #include <condition_variable>
#include <deque> #include <deque>
#include <fstream> #include <fstream>
@@ -80,11 +80,16 @@ public:
const double bitrate_multiplier; const double bitrate_multiplier;
private: private:
std::mutex mutex; using state_t = std::atomic_unsigned_lock_free::value_type;
std::array<std::atomic<bool>, num_slots> busy = {false, false}; static const state_t idle = 0;
static const state_t busy = 1;
static const state_t skip = 2;
std::array<std::atomic_unsigned_lock_free, num_slots> state = {idle, idle};
uint8_t present_slot = 0; uint8_t present_slot = 0;
uint8_t encode_slot = 0; uint8_t encode_slot = 0;
std::mutex mutex;
// temporary data // temporary data
wivrn_session * cnx; wivrn_session * cnx;
@@ -94,9 +99,6 @@ private:
to_headset::video_stream_data_shard::timing_info_t timing_info; to_headset::video_stream_data_shard::timing_info_t timing_info;
clock_offset clock; clock_offset clock;
std::atomic_bool sync_needed = true;
uint64_t last_idr_frame;
std::ofstream video_dump; std::ofstream video_dump;
std::shared_ptr<sender> shared_sender; std::shared_ptr<sender> shared_sender;
@@ -104,6 +106,7 @@ private:
protected: protected:
std::atomic_int pending_bitrate; std::atomic_int pending_bitrate;
std::atomic<float> pending_framerate; std::atomic<float> pending_framerate;
std::unique_ptr<idr_handler> idr;
public: public:
static std::unique_ptr<video_encoder> create( static std::unique_ptr<video_encoder> create(
@@ -114,7 +117,7 @@ public:
int input_height, int input_height,
float fps); float fps);
video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, double bitrate_multiplier, bool async_send); video_encoder(uint8_t stream_idx, to_headset::video_stream_description::channels_t channels, std::unique_ptr<idr_handler>, double bitrate_multiplier, bool async_send);
virtual ~video_encoder(); virtual ~video_encoder();
// return value: true if image should be transitioned to queue and layout for vulkan video encode // return value: true if image should be transitioned to queue and layout for vulkan video encode
@@ -122,8 +125,9 @@ public:
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint64_t frame_index); std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint64_t frame_index);
void post_submit(); void post_submit();
virtual void on_feedback(const from_headset::feedback &); void on_feedback(const from_headset::feedback &);
virtual void reset(); void reset();
void set_bitrate(int bitrate_bps); void set_bitrate(int bitrate_bps);
void set_framerate(float framerate); void set_framerate(float framerate);
@@ -136,7 +140,7 @@ public:
// called after command buffer passed in present_image was submitted // called after command buffer passed in present_image was submitted
virtual void post_submit(uint8_t slot) {} virtual void post_submit(uint8_t slot) {}
// called when command buffer finished executing // called when command buffer finished executing
virtual std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point target_timestamp, uint8_t slot) = 0; virtual std::optional<data> encode(uint8_t slot, uint64_t frame_index) = 0;
void SendData(std::span<uint8_t> data, bool end_of_frame, bool control = false); void SendData(std::span<uint8_t> data, bool end_of_frame, bool control = false);
}; };
+16 -4
View File
@@ -151,7 +151,7 @@ video_encoder_nvenc::video_encoder_nvenc(
encoder_settings & settings, encoder_settings & settings,
float fps, float fps,
uint8_t stream_idx) : uint8_t stream_idx) :
video_encoder(stream_idx, settings.channels, settings.bitrate_multiplier, true), video_encoder(stream_idx, settings.channels, std::make_unique<default_idr_handler>(), settings.bitrate_multiplier, true),
vk(vk), vk(vk),
shared_state(video_encoder_nvenc_shared_state::get()), shared_state(video_encoder_nvenc_shared_state::get()),
fps(fps), fps(fps),
@@ -420,9 +420,10 @@ std::pair<bool, vk::Semaphore> video_encoder_nvenc::present_image(vk::Image y_cb
return {false, nullptr}; return {false, nullptr};
} }
std::optional<video_encoder::data> video_encoder_nvenc::encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) std::optional<video_encoder::data> video_encoder_nvenc::encode(uint8_t slot, uint64_t frame_index)
{ {
CU_CHECK(shared_state->cuda_fn->cuCtxPushCurrent(shared_state->cuda)); CU_CHECK(shared_state->cuda_fn->cuCtxPushCurrent(shared_state->cuda));
auto & idr_handler = ((default_idr_handler &)*idr);
auto new_bitrate = pending_bitrate.exchange(0); auto new_bitrate = pending_bitrate.exchange(0);
auto new_framerate = pending_framerate.exchange(0); auto new_framerate = pending_framerate.exchange(0);
@@ -453,7 +454,7 @@ std::optional<video_encoder::data> video_encoder_nvenc::encode(bool idr, std::ch
NVENC_CHECK(shared_state->fn.nvEncReconfigureEncoder(session_handle, &reconfig_params)); NVENC_CHECK(shared_state->fn.nvEncReconfigureEncoder(session_handle, &reconfig_params));
fps = new_framerate; fps = new_framerate;
bitrate = new_bitrate; bitrate = new_bitrate;
idr = true; idr_handler.reset();
U_LOG_I("nvenc: reconfiguring succeeded."); U_LOG_I("nvenc: reconfiguring succeeded.");
} }
@@ -476,7 +477,7 @@ std::optional<video_encoder::data> video_encoder_nvenc::encode(bool idr, std::ch
.inputWidth = rect.extent.width, .inputWidth = rect.extent.width,
.inputHeight = rect.extent.height, .inputHeight = rect.extent.height,
.inputPitch = rect.extent.width, .inputPitch = rect.extent.width,
.encodePicFlags = uint32_t(idr ? NV_ENC_PIC_FLAG_FORCEIDR | NV_ENC_PIC_FLAG_OUTPUT_SPSPPS : 0), .encodePicFlags = 0,
.frameIdx = 0, .frameIdx = 0,
.inputTimeStamp = 0, .inputTimeStamp = 0,
.inputBuffer = inp_resource_params.mappedResource, .inputBuffer = inp_resource_params.mappedResource,
@@ -484,6 +485,16 @@ std::optional<video_encoder::data> video_encoder_nvenc::encode(bool idr, std::ch
.bufferFmt = inp_resource_params.mappedBufferFmt, .bufferFmt = inp_resource_params.mappedBufferFmt,
.pictureStruct = NV_ENC_PIC_STRUCT_FRAME, .pictureStruct = NV_ENC_PIC_STRUCT_FRAME,
}; };
auto frame_type = idr_handler.get_type(frame_index);
switch (frame_type)
{
case default_idr_handler::frame_type::i:
frame_params.encodePicFlags |= NV_ENC_PIC_FLAG_FORCEIDR | NV_ENC_PIC_FLAG_OUTPUT_SPSPPS;
break;
case default_idr_handler::frame_type::p:
break;
}
NVENC_CHECK(shared_state->fn.nvEncEncodePicture(session_handle, &frame_params)); NVENC_CHECK(shared_state->fn.nvEncEncodePicture(session_handle, &frame_params));
NV_ENC_LOCK_BITSTREAM buf_lock_params{ NV_ENC_LOCK_BITSTREAM buf_lock_params{
@@ -502,6 +513,7 @@ std::optional<video_encoder::data> video_encoder_nvenc::encode(bool idr, std::ch
if (status != NV_ENC_SUCCESS) if (status != NV_ENC_SUCCESS)
U_LOG_E("%s:%d: %d, %s", __FILE__, __LINE__, status, shared_state->fn.nvEncGetLastErrorString(session_handle)); U_LOG_E("%s:%d: %d, %s", __FILE__, __LINE__, status, shared_state->fn.nvEncGetLastErrorString(session_handle));
}), }),
.prefer_control = frame_type == default_idr_handler::frame_type::i,
}; };
} }
+1 -1
View File
@@ -64,7 +64,7 @@ public:
~video_encoder_nvenc(); ~video_encoder_nvenc();
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) override; std::optional<data> encode(uint8_t slot, uint64_t frame_index) override;
static std::array<int, 2> get_max_size(video_codec); static std::array<int, 2> get_max_size(video_codec);
}; };
+16 -2
View File
@@ -21,12 +21,26 @@
#include "encoder/encoder_settings.h" #include "encoder/encoder_settings.h"
#include "utils/wivrn_vk_bundle.h" #include "utils/wivrn_vk_bundle.h"
namespace
{
class dummy_idr_handler : public wivrn::idr_handler
{
public:
void on_feedback(const wivrn::from_headset::feedback &) override {};
void reset() override {};
bool should_skip(uint64_t frame_id) override
{
return false;
};
};
} // namespace
wivrn::video_encoder_raw::video_encoder_raw( wivrn::video_encoder_raw::video_encoder_raw(
wivrn_vk_bundle & vk, wivrn_vk_bundle & vk,
encoder_settings & settings, encoder_settings & settings,
float fps, float fps,
uint8_t stream_idx) : uint8_t stream_idx) :
video_encoder(stream_idx, settings.channels, settings.bitrate_multiplier, true) video_encoder(stream_idx, settings.channels, std::make_unique<dummy_idr_handler>(), settings.bitrate_multiplier, true)
{ {
if (settings.bit_depth != 8) if (settings.bit_depth != 8)
throw std::runtime_error("Raw encoding is only supported for 8 bit"); throw std::runtime_error("Raw encoding is only supported for 8 bit");
@@ -112,7 +126,7 @@ std::pair<bool, vk::Semaphore> wivrn::video_encoder_raw::present_image(vk::Image
return {false, nullptr}; return {false, nullptr};
} }
std::optional<wivrn::video_encoder::data> wivrn::video_encoder_raw::encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) std::optional<wivrn::video_encoder::data> wivrn::video_encoder_raw::encode(uint8_t slot, uint64_t frame_id)
{ {
return wivrn::video_encoder::data{ return wivrn::video_encoder::data{
.encoder = this, .encoder = this,
+1 -1
View File
@@ -36,6 +36,6 @@ public:
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) override; std::optional<data> encode(uint8_t slot, uint64_t frame_id) override;
}; };
} // namespace wivrn } // namespace wivrn
+153 -81
View File
@@ -25,6 +25,107 @@
#include <iostream> #include <iostream>
#include <stdexcept> #include <stdexcept>
namespace
{
class dpb_state : public wivrn::idr_handler
{
public:
struct dpb_item
{
vk::raii::ImageView image_view;
vk::VideoPictureResourceInfoKHR resource;
vk::VideoReferenceSlotInfoKHR & info;
uint64_t frame_index = -1;
bool acked = false;
};
std::vector<dpb_item> items;
std::vector<vk::VideoReferenceSlotInfoKHR> infos;
uint32_t frame_num = 0;
std::mutex mutex;
void on_feedback(const wivrn::from_headset::feedback & feedback) override
{
if (feedback.sent_to_decoder)
{
std::unique_lock lock(mutex);
for (auto & item: items)
{
if (item.frame_index == feedback.frame_index)
{
item.acked = true;
return;
}
}
}
}
void reset() override
{
std::unique_lock lock(mutex);
for (auto & item: items)
{
item.frame_index = -1;
item.info.pPictureResource = nullptr;
item.info.slotIndex = -1;
item.acked = false;
}
}
bool should_skip(uint64_t frame_id) override
{
std::unique_lock lock(mutex);
bool pending = false; // has any data been sent?
for (auto & i: items)
{
if (i.acked)
return false;
if (i.info.slotIndex != -1)
pending = true;
}
return pending;
}
std::pair<dpb_item *, dpb_item *> get_ref(uint64_t frame_index)
{
// must hold the lock
auto slot = std::ranges::min_element(
items,
[](const auto & a, const auto & b) {
return a.frame_index + 1 < b.frame_index + 1;
});
slot->info.slotIndex = -1;
dpb_item * ref_slot = nullptr;
for (auto & i: items)
{
if (i.info.slotIndex == -1 or not i.acked)
continue;
if (ref_slot and ref_slot->frame_index > i.frame_index)
continue;
ref_slot = &i;
}
if (not ref_slot)
{
frame_num = 0;
for (auto & slot: items)
{
slot.info.slotIndex = -1;
slot.info.pPictureResource = nullptr;
slot.frame_index = -1;
slot.acked = false;
}
}
slot->acked = false;
slot->frame_index = frame_index;
slot->info.pPictureResource = &slot->resource;
return {ref_slot, &*slot};
}
};
} // namespace
static uint32_t align(uint32_t value, uint32_t alignment) static uint32_t align(uint32_t value, uint32_t alignment)
{ {
if (alignment == 0) if (alignment == 0)
@@ -62,7 +163,7 @@ wivrn::video_encoder_vulkan::video_encoder_vulkan(
float fps, float fps,
uint8_t stream_idx, uint8_t stream_idx,
const encoder_settings & settings) : const encoder_settings & settings) :
video_encoder(stream_idx, settings.channels, settings.bitrate_multiplier, true), video_encoder(stream_idx, settings.channels, std::make_unique<dpb_state>(), settings.bitrate_multiplier, true),
vk(vk), vk(vk),
encode_caps(patch_capabilities(in_encode_caps)), encode_caps(patch_capabilities(in_encode_caps)),
rect(rect), rect(rect),
@@ -115,6 +216,18 @@ wivrn::video_encoder_vulkan::video_encoder_vulkan(
U_LOG_W("No suitable rate control available, reverting to default"); U_LOG_W("No suitable rate control available, reverting to default");
rate_control.reset(); rate_control.reset();
} }
constexpr uint32_t cb_min_size = 8;
uint32_t granWidth =
std::max(video_caps.pictureAccessGranularity.width, encode_caps.encodeInputPictureGranularity.width);
uint32_t granHeight =
std::max(video_caps.pictureAccessGranularity.height, encode_caps.encodeInputPictureGranularity.height);
aligned_extent = vk::Extent3D{
.width = align(rect.extent.width, std::max(cb_min_size, granWidth)),
.height = align(rect.extent.height, std::max(cb_min_size, granHeight)),
.depth = 1,
};
} }
void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_caps, void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_caps,
@@ -135,7 +248,7 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
.imageUsage = vk::ImageUsageFlagBits::eVideoEncodeSrcKHR, .imageUsage = vk::ImageUsageFlagBits::eVideoEncodeSrcKHR,
}); });
if (picture_format.format != vk::Format::eG8B8R82Plane420Unorm) if (picture_format.format != vk::Format::eG8B8R82Plane420Unorm && picture_format.format != vk::Format::eG10X6B10X6R10X62Plane420Unorm3Pack16)
throw std::runtime_error("Unsupported format " + throw std::runtime_error("Unsupported format " +
vk::to_string(picture_format.format) + vk::to_string(picture_format.format) +
" for encoder input image"); " for encoder input image");
@@ -151,12 +264,6 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
// TODO: check format capabilities // TODO: check format capabilities
// TODO: use multiple images if array levels are not supported // TODO: use multiple images if array levels are not supported
vk::Extent3D aligned_extent{
.width = align(rect.extent.width, video_caps.pictureAccessGranularity.width),
.height = align(rect.extent.height, video_caps.pictureAccessGranularity.height),
.depth = 1,
};
vk::ImageCreateInfo img_create_info{ vk::ImageCreateInfo img_create_info{
.pNext = &video_profile_list, .pNext = &video_profile_list,
.flags = reference_picture_format.imageCreateFlags, .flags = reference_picture_format.imageCreateFlags,
@@ -224,10 +331,10 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
//.flags = vk::VideoSessionCreateFlagBitsKHR::eAllowEncodeParameterOptimizations, //.flags = vk::VideoSessionCreateFlagBitsKHR::eAllowEncodeParameterOptimizations,
.pVideoProfile = &video_profile, .pVideoProfile = &video_profile,
.pictureFormat = picture_format.format, .pictureFormat = picture_format.format,
.maxCodedExtent = rect.extent, .maxCodedExtent = {aligned_extent.width, aligned_extent.height},
.referencePictureFormat = reference_picture_format.format, .referencePictureFormat = reference_picture_format.format,
.maxDpbSlots = num_dpb_slots, .maxDpbSlots = num_dpb_slots,
.maxActiveReferencePictures = 2, .maxActiveReferencePictures = 1, // h265 code assumes only 1 reference
.pStdHeaderVersion = &std_header_version, .pStdHeaderVersion = &std_header_version,
}); });
@@ -300,13 +407,15 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
} }
} }
auto & dpb = (dpb_state &)*idr;
// DPB slot info // DPB slot info
{ {
auto std_slots = setup_slot_info(num_dpb_slots); auto std_slots = setup_slot_info(num_dpb_slots);
assert(std_slots.size() == num_dpb_slots); assert(std_slots.size() == num_dpb_slots);
for (size_t i = 0; i < num_dpb_slots; ++i) for (size_t i = 0; i < num_dpb_slots; ++i)
{ {
dpb_info.push_back({ dpb.infos.push_back({
.pNext = std_slots[i], .pNext = std_slots[i],
.slotIndex = -1, .slotIndex = -1,
.pPictureResource = nullptr, .pPictureResource = nullptr,
@@ -329,23 +438,17 @@ void wivrn::video_encoder_vulkan::init(const vk::VideoCapabilitiesKHR & video_ca
for (size_t i = 0; i < num_dpb_slots; ++i) for (size_t i = 0; i < num_dpb_slots; ++i)
{ {
img_view_create_info.subresourceRange.baseArrayLayer = i; img_view_create_info.subresourceRange.baseArrayLayer = i;
dpb.push_back( vk::raii::ImageView v(vk.device, img_view_create_info);
{ vk::ImageView v1(*v);
.image_view = vk.device.createImageView(img_view_create_info), vk.name(v, "vulkan encoder dpb view");
.info = dpb_info[i], dpb.items.push_back({
}); .image_view = std::move(v),
vk.name(dpb.back().image_view, "vulkan encoder dpb view"); .resource = {
} .codedExtent = rect.extent,
} .imageViewBinding = v1,
},
// DPB video picture resource info .info = dpb.infos[i],
{ });
for (auto & item: dpb)
{
item.resource = vk::VideoPictureResourceInfoKHR{
.codedExtent = rect.extent,
.imageViewBinding = *item.image_view,
};
} }
} }
@@ -442,10 +545,8 @@ std::vector<uint8_t> wivrn::video_encoder_vulkan::get_encoded_parameters(void *
return encoded; return encoded;
} }
std::optional<wivrn::video_encoder::data> wivrn::video_encoder_vulkan::encode(bool idr, std::chrono::steady_clock::time_point target_timestamp, uint8_t encode_slot) std::optional<wivrn::video_encoder::data> wivrn::video_encoder_vulkan::encode(uint8_t encode_slot, uint64_t frame_index)
{ {
// we manage idrs ourselves
(void)idr;
auto & slot_item = slot_data[encode_slot]; auto & slot_item = slot_data[encode_slot];
if (slot_item.idr) if (slot_item.idr)
send_idr_data(); send_idr_data();
@@ -632,52 +733,32 @@ std::pair<bool, vk::Semaphore> wivrn::video_encoder_vulkan::present_image(vk::Im
video_cmd_buf.resetQueryPool(*query_pool, encode_slot, 1); video_cmd_buf.resetQueryPool(*query_pool, encode_slot, 1);
auto slot = std::ranges::min_element( auto & dpb = (dpb_state &)*idr;
dpb, std::unique_lock lock(dpb.mutex);
[](const auto & a, const auto & b) { auto [ref_slot, slot] = dpb.get_ref(frame_index);
return a.frame_index + 1 < b.frame_index + 1; slot_item.idr = ref_slot == nullptr;
});
size_t slot_index = std::distance(dpb.begin(), slot);
slot->info.slotIndex = -1;
auto last_ack = this->last_ack.load(); vk::VideoReferenceSlotInfoKHR init_refs[2] = {};
dpb_item * ref_slot = nullptr; init_refs[0] = slot->info;
for (auto & i: dpb) init_refs[0].slotIndex = -1;
{ init_refs[0].pPictureResource = &slot->resource;
if (i.frame_index == last_ack and i.info.slotIndex != -1)
{
ref_slot = &i;
break;
}
}
if (not ref_slot) if (ref_slot)
{ {
frame_num = 0; init_refs[1] = ref_slot->info;
for (auto & slot: dpb) init_refs[1].slotIndex = ref_slot->info.slotIndex;
{ init_refs[1].pPictureResource = &ref_slot->resource;
slot.info.slotIndex = -1;
slot.info.pPictureResource = nullptr;
slot.frame_index = -1;
}
slot_item.idr = true;
last_ack = frame_index;
} }
else
{
slot_item.idr = false;
}
slot->frame_index = frame_index;
slot->info.pPictureResource = &slot->resource;
video_cmd_buf.beginVideoCodingKHR({ video_cmd_buf.beginVideoCodingKHR({
.pNext = (session_initialized and rate_control) ? &rate_control.value() : nullptr, .pNext = (session_initialized and rate_control) ? &rate_control.value() : nullptr,
.videoSession = *video_session, .videoSession = *video_session,
.videoSessionParameters = *video_session_parameters, .videoSessionParameters = *video_session_parameters,
.referenceSlotCount = uint32_t(dpb_info.size()), .referenceSlotCount = ref_slot ? 2u : 1u,
.pReferenceSlots = dpb_info.data(), .pReferenceSlots = init_refs,
}); });
size_t slot_index = std::distance(dpb.items.data(), slot);
slot->info.slotIndex = slot_index; slot->info.slotIndex = slot_index;
if (not session_initialized) if (not session_initialized)
@@ -706,7 +787,7 @@ std::pair<bool, vk::Semaphore> wivrn::video_encoder_vulkan::present_image(vk::Im
.baseMipLevel = 0, .baseMipLevel = 0,
.levelCount = 1, .levelCount = 1,
.baseArrayLayer = 0, .baseArrayLayer = 0,
.layerCount = uint32_t(dpb.size())}, .layerCount = vk::RemainingArrayLayers},
}; };
video_cmd_buf.pipelineBarrier2({ video_cmd_buf.pipelineBarrier2({
.imageMemoryBarrierCount = 1, .imageMemoryBarrierCount = 1,
@@ -746,17 +827,19 @@ std::pair<bool, vk::Semaphore> wivrn::video_encoder_vulkan::present_image(vk::Im
}); });
vk::VideoEncodeInfoKHR encode_info{ vk::VideoEncodeInfoKHR encode_info{
.pNext = encode_info_next(frame_num, slot_index, ref_slot ? std::make_optional(ref_slot->info.slotIndex) : std::nullopt), .pNext = encode_info_next(dpb.frame_num, slot_index, ref_slot ? std::make_optional(ref_slot->info.slotIndex) : std::nullopt),
.dstBuffer = slot_item.output_buffer, .dstBuffer = slot_item.output_buffer,
.dstBufferOffset = 0, .dstBufferOffset = 0,
.dstBufferRange = slot_item.output_buffer.info().size, .dstBufferRange = slot_item.output_buffer.info().size,
.srcPictureResource = { .srcPictureResource = {
.codedExtent = rect.extent, .codedOffset = {0, 0},
.codedExtent = {aligned_extent.width, aligned_extent.height},
.baseArrayLayer = 0, .baseArrayLayer = 0,
.imageViewBinding = image_view, .imageViewBinding = image_view,
}, },
.pSetupReferenceSlot = &slot->info, .pSetupReferenceSlot = &slot->info,
}; };
if (ref_slot) if (ref_slot)
encode_info.setReferenceSlots(ref_slot->info); encode_info.setReferenceSlots(ref_slot->info);
@@ -832,7 +915,7 @@ std::pair<bool, vk::Semaphore> wivrn::video_encoder_vulkan::present_image(vk::Im
video_cmd_buf.end(); video_cmd_buf.end();
++frame_num; ++dpb.frame_num;
// If we encode directly from the source, request a transition to video queue // If we encode directly from the source, request a transition to video queue
return {encode_direct, slot_item.wait_sem}; return {encode_direct, slot_item.wait_sem};
@@ -879,14 +962,3 @@ void wivrn::video_encoder_vulkan::post_submit(uint8_t slot)
*slot_item.fence); *slot_item.fence);
} }
} }
void wivrn::video_encoder_vulkan::on_feedback(const from_headset::feedback & feedback)
{
if (feedback.sent_to_decoder)
{
auto prev = last_ack.load();
while (prev < feedback.frame_index and last_ack.compare_exchange_weak(prev, feedback.frame_index))
{
}
}
}
+3 -15
View File
@@ -20,6 +20,7 @@
#include <unordered_map> #include <unordered_map>
#include <vector> #include <vector>
#include <vulkan/vulkan_raii.hpp> #include <vulkan/vulkan_raii.hpp>
#include <vulkan/vulkan_structs.hpp>
#include "video_encoder.h" #include "video_encoder.h"
#include "vk/allocation.h" #include "vk/allocation.h"
@@ -58,30 +59,18 @@ class video_encoder_vulkan : public video_encoder
image_allocation dpb_image; image_allocation dpb_image;
struct dpb_item
{
vk::raii::ImageView image_view;
vk::VideoPictureResourceInfoKHR resource;
vk::VideoReferenceSlotInfoKHR & info;
uint64_t frame_index = -1;
};
std::vector<dpb_item> dpb;
std::vector<vk::VideoReferenceSlotInfoKHR> dpb_info;
std::vector<vk::raii::DeviceMemory> mem; std::vector<vk::raii::DeviceMemory> mem;
vk::VideoFormatPropertiesKHR select_video_format( vk::VideoFormatPropertiesKHR select_video_format(
vk::raii::PhysicalDevice & physical_device, vk::raii::PhysicalDevice & physical_device,
const vk::PhysicalDeviceVideoFormatInfoKHR &); const vk::PhysicalDeviceVideoFormatInfoKHR &);
uint32_t frame_num = 0;
std::atomic<uint64_t> last_ack = 0;
bool session_initialized = false; bool session_initialized = false;
const vk::Rect2D rect; const vk::Rect2D rect;
protected: protected:
const uint8_t num_dpb_slots; const uint8_t num_dpb_slots;
vk::Extent3D aligned_extent;
vk::VideoEncodeRateControlLayerInfoKHR rate_control_layer; vk::VideoEncodeRateControlLayerInfoKHR rate_control_layer;
std::optional<vk::VideoEncodeRateControlInfoKHR> rate_control; std::optional<vk::VideoEncodeRateControlInfoKHR> rate_control;
@@ -109,9 +98,8 @@ protected:
virtual vk::ExtensionProperties std_header_version() = 0; virtual vk::ExtensionProperties std_header_version() = 0;
public: public:
std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point target_timestamp, uint8_t slot) override; std::optional<data> encode(uint8_t slot, uint64_t frame_index) override;
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
void post_submit(uint8_t slot) override; void post_submit(uint8_t slot) override;
void on_feedback(const from_headset::feedback &) override;
}; };
} // namespace wivrn } // namespace wivrn
+2 -1
View File
@@ -16,6 +16,7 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include "video_encoder_vulkan_h264.h" #include "video_encoder_vulkan_h264.h"
#include "encoder/encoder_settings.h" #include "encoder/encoder_settings.h"
#include "utils/wivrn_vk_bundle.h" #include "utils/wivrn_vk_bundle.h"
@@ -337,7 +338,7 @@ void * wivrn::video_encoder_vulkan_h264::encode_info_next(uint32_t frame_num, si
std_picture_info = { std_picture_info = {
.flags = .flags =
{ {
.IdrPicFlag = uint32_t(ref_slot ? 0 : 1), .IdrPicFlag = ref_slot ? 0u : 1u,
.is_reference = 1, .is_reference = 1,
.no_output_of_prior_pics_flag = 0, .no_output_of_prior_pics_flag = 0,
.long_term_reference_flag = 0, .long_term_reference_flag = 0,
+292 -214
View File
@@ -17,15 +17,90 @@
* along with this program. If not, see <https://www.gnu.org/licenses/>. * along with this program. If not, see <https://www.gnu.org/licenses/>.
*/ */
#include "video_encoder_vulkan_h265.h" #include "video_encoder_vulkan_h265.h"
#include "encoder/encoder_settings.h"
#include "util/u_logging.h"
#include "utils/wivrn_vk_bundle.h"
wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk, vk::Rect2D rect, vk::VideoEncodeCapabilitiesKHR encode_caps, float fps, uint64_t bitrate) : #include "encoder/encoder_settings.h"
video_encoder_vulkan(vk, rect, encode_caps, fps, bitrate), #include "utils/wivrn_vk_bundle.h"
#include <cstdint>
#include <vulkan/vulkan_core.h>
#include <vulkan/vulkan_enums.hpp>
static StdVideoH265LevelIdc choose_level(uint32_t w, uint32_t h, float fps)
{
const uint64_t pixrate = uint64_t(w) * uint64_t(h) * uint64_t(fps + 0.5f);
// only consider >=5_0 due to general_tier_flag on ptl
if (pixrate < 267'386'880)
return STD_VIDEO_H265_LEVEL_IDC_5_0;
if (pixrate < 534'773'760)
return STD_VIDEO_H265_LEVEL_IDC_5_1;
if (pixrate < 1'069'547'520)
return STD_VIDEO_H265_LEVEL_IDC_6_0;
if (pixrate < 2'139'095'040)
return STD_VIDEO_H265_LEVEL_IDC_6_1;
return STD_VIDEO_H265_LEVEL_IDC_6_2;
}
static uint32_t find_lsb(uint32_t v)
{
for (int i = 0; i < 32; i++)
if (v & (1u << i))
return i;
throw std::runtime_error(std::string("invalid value in encode capabilities reported by gpu driver"));
}
static uint32_t find_msb(uint32_t v)
{
for (int i = 31; i >= 0; i--)
if (v & (1u << i))
return i;
throw std::runtime_error(std::string("invalid value in encode capabilities reported by gpu driver"));
}
wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(
wivrn_vk_bundle & vk,
vk::Rect2D rect,
const vk::VideoCapabilitiesKHR & video_caps,
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
float fps,
uint8_t stream_idx,
const encoder_settings & settings) :
video_encoder_vulkan(vk, rect, video_caps, encode_caps, fps, stream_idx, settings),
vui{
.flags = {
.aspect_ratio_info_present_flag = 1,
.video_signal_type_present_flag = 1,
.video_full_range_flag = 1,
.colour_description_present_flag = 1,
.chroma_loc_info_present_flag = 1,
.vui_timing_info_present_flag = 0, // no fixed framerate
.motion_vectors_over_pic_boundaries_flag = 1, // allow motion vectors that exceed picture boundaries
.restricted_ref_pic_lists_flag = 1, // all slices in a single picture use the same referene
},
.aspect_ratio_idc = STD_VIDEO_H265_ASPECT_RATIO_IDC_SQUARE, // _pixels_ are square
.video_format = 5, // unspecified video format
.colour_primaries = 1, // BT.709
.transfer_characteristics = 1, // BT.709
.matrix_coeffs = 1, // BT.709
.chroma_sample_loc_type_top_field = 0,
.chroma_sample_loc_type_bottom_field = 0,
},
dpb{.max_latency_increase_plus1 = {1}, .max_dec_pic_buffering_minus1 = {uint8_t(num_dpb_slots > 0 ? num_dpb_slots - 1 : 0)}, .max_num_reorder_pics = {0}},
ptl{.flags = {
.general_tier_flag = 1, // 1 if >=STD_VIDEO_H265_LEVEL_IDC_5_0 and we only do 5 and above
.general_progressive_source_flag = 1,
.general_interlaced_source_flag = 0,
.general_non_packed_constraint_flag = 0,
.general_frame_only_constraint_flag = 1,
},
.general_profile_idc = (settings.bit_depth == 10) ? STD_VIDEO_H265_PROFILE_IDC_MAIN_10 : STD_VIDEO_H265_PROFILE_IDC_MAIN,
.general_level_idc = choose_level(rect.extent.width, rect.extent.height, fps)},
vps{ vps{
.flags{ .flags = {
.vps_temporal_id_nesting_flag = 0, .vps_temporal_id_nesting_flag = 1, // radv breaks without
.vps_sub_layer_ordering_info_present_flag = 0, .vps_sub_layer_ordering_info_present_flag = 0,
.vps_timing_info_present_flag = 0, .vps_timing_info_present_flag = 0,
.vps_poc_proportional_to_timing_flag = 0, .vps_poc_proportional_to_timing_flag = 0,
@@ -37,55 +112,31 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk
.vps_num_units_in_tick = 0, .vps_num_units_in_tick = 0,
.vps_time_scale = 0, .vps_time_scale = 0,
.vps_num_ticks_poc_diff_one_minus1 = 0, .vps_num_ticks_poc_diff_one_minus1 = 0,
.reserved3 = 0,
.pDecPicBufMgr = &dpb,
.pHrdParameters = nullptr,
.pProfileTierLevel = &ptl,
}, },
sps{ sps{
.flags{ .flags = {
.sps_temporal_id_nesting_flag = 0, .sps_temporal_id_nesting_flag = 1, // radv breaks without
.separate_colour_plane_flag = 0, .conformance_window_flag = 1, // conf_win_* are set
.conformance_window_flag = 0, .amp_enabled_flag = 1, // confirmed ok
.sps_sub_layer_ordering_info_present_flag = 0, .sample_adaptive_offset_enabled_flag = 0, // off for (ultra) low-latency
.scaling_list_enabled_flag = 0, .strong_intra_smoothing_enabled_flag = 1, // confirmed ok
.sps_scaling_list_data_present_flag = 0, .vui_parameters_present_flag = 1,
.amp_enabled_flag = 0, .sps_range_extension_flag = (settings.bit_depth == 10) ? 1u : 0u,
.sample_adaptive_offset_enabled_flag = 0,
.pcm_enabled_flag = 0,
.pcm_loop_filter_disabled_flag = 0,
.long_term_ref_pics_present_flag = 0,
.sps_temporal_mvp_enabled_flag = 0,
.strong_intra_smoothing_enabled_flag = 0,
.vui_parameters_present_flag = 0,
.sps_extension_present_flag = 0,
.sps_range_extension_flag = 0,
.transform_skip_rotation_enabled_flag = 0,
.transform_skip_context_enabled_flag = 0,
.implicit_rdpcm_enabled_flag = 0,
.explicit_rdpcm_enabled_flag = 0,
.extended_precision_processing_flag = 0,
.intra_smoothing_disabled_flag = 0,
.high_precision_offsets_enabled_flag = 0,
.persistent_rice_adaptation_enabled_flag = 0,
.cabac_bypass_alignment_enabled_flag = 0,
.sps_scc_extension_flag = 0,
.sps_curr_pic_ref_enabled_flag = 0,
.palette_mode_enabled_flag = 0,
.sps_palette_predictor_initializers_present_flag = 0,
.intra_boundary_filtering_disabled_flag = 0,
}, },
.chroma_format_idc = STD_VIDEO_H265_CHROMA_FORMAT_IDC_420, .chroma_format_idc = STD_VIDEO_H265_CHROMA_FORMAT_IDC_420,
.pic_width_in_luma_samples = 0, .pic_width_in_luma_samples = aligned_extent.width, // confirmed
.pic_height_in_luma_samples = 0, .pic_height_in_luma_samples = aligned_extent.height, // confirmed
.sps_video_parameter_set_id = 0, .sps_video_parameter_set_id = 0,
.sps_max_sub_layers_minus1 = 0, .sps_max_sub_layers_minus1 = 0,
.sps_seq_parameter_set_id = 0, .sps_seq_parameter_set_id = 0,
.bit_depth_luma_minus8 = 0, .bit_depth_luma_minus8 = static_cast<uint8_t>(settings.bit_depth - 8),
.bit_depth_chroma_minus8 = 0, .bit_depth_chroma_minus8 = static_cast<uint8_t>(settings.bit_depth - 8),
.log2_max_pic_order_cnt_lsb_minus4 = 0, .log2_max_pic_order_cnt_lsb_minus4 = 4, // arbitrary
.log2_min_luma_coding_block_size_minus3 = 0, .log2_min_luma_coding_block_size_minus3 = 0, // keep it 0, related values are filled in create()
.log2_diff_max_min_luma_coding_block_size = 0,
.log2_min_luma_transform_block_size_minus2 = 0,
.log2_diff_max_min_luma_transform_block_size = 0,
.max_transform_hierarchy_depth_inter = 0,
.max_transform_hierarchy_depth_intra = 0,
.num_short_term_ref_pic_sets = 0, .num_short_term_ref_pic_sets = 0,
.num_long_term_ref_pics_sps = 0, .num_long_term_ref_pics_sps = 0,
.pcm_sample_bit_depth_luma_minus1 = 0, .pcm_sample_bit_depth_luma_minus1 = 0,
@@ -98,46 +149,26 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk
.delta_palette_max_predictor_size = 0, .delta_palette_max_predictor_size = 0,
.motion_vector_resolution_control_idc = 0, .motion_vector_resolution_control_idc = 0,
.sps_num_palette_predictor_initializers_minus1 = 0, .sps_num_palette_predictor_initializers_minus1 = 0,
.conf_win_left_offset = 0, .conf_win_left_offset = 0u,
.conf_win_right_offset = 0, .conf_win_right_offset = (aligned_extent.width - rect.extent.width) >> 1, // 4:2:0
.conf_win_top_offset = 0, .conf_win_top_offset = 0u,
.conf_win_bottom_offset = 0, .conf_win_bottom_offset = (aligned_extent.height - rect.extent.height) >> 1, // 4:2:0
.pProfileTierLevel = &ptl,
.pDecPicBufMgr = &dpb,
.pScalingLists = nullptr,
.pShortTermRefPicSet = nullptr,
.pLongTermRefPicsSps = nullptr,
.pSequenceParameterSetVui = &vui,
.pPredictorPaletteEntries = nullptr,
}, },
pps{ pps{
.flags = .flags = {
{ .cu_qp_delta_enabled_flag = 1, // must be 1 or nvidia breaks
.dependent_slice_segments_enabled_flag = 0, .transquant_bypass_enabled_flag = 0, // only 1 when tuned for lossless
.output_flag_present_flag = 0, .deblocking_filter_control_present_flag = 1,
.sign_data_hiding_enabled_flag = 0, .pps_range_extension_flag = (settings.bit_depth == 10) ? 1u : 0u,
.cabac_init_present_flag = 0, },
.constrained_intra_pred_flag = 0,
.transform_skip_enabled_flag = 0,
.cu_qp_delta_enabled_flag = 0,
.pps_slice_chroma_qp_offsets_present_flag = 0,
.weighted_pred_flag = 0,
.weighted_bipred_flag = 0,
.transquant_bypass_enabled_flag = 0,
.tiles_enabled_flag = 0,
.entropy_coding_sync_enabled_flag = 0,
.uniform_spacing_flag = 0,
.loop_filter_across_tiles_enabled_flag = 0,
.pps_loop_filter_across_slices_enabled_flag = 0,
.deblocking_filter_control_present_flag = 0,
.deblocking_filter_override_enabled_flag = 0,
.pps_deblocking_filter_disabled_flag = 0,
.pps_scaling_list_data_present_flag = 0,
.lists_modification_present_flag = 0,
.slice_segment_header_extension_present_flag = 0,
.pps_extension_present_flag = 0,
.cross_component_prediction_enabled_flag = 0,
.chroma_qp_offset_list_enabled_flag = 0,
.pps_curr_pic_ref_enabled_flag = 0,
.residual_adaptive_colour_transform_enabled_flag = 0,
.pps_slice_act_qp_offsets_present_flag = 0,
.pps_palette_predictor_initializers_present_flag = 0,
.monochrome_palette_flag = 0,
.pps_range_extension_flag = 0,
},
.pps_pic_parameter_set_id = 0, .pps_pic_parameter_set_id = 0,
.pps_seq_parameter_set_id = 0, .pps_seq_parameter_set_id = 0,
.sps_video_parameter_set_id = 0, .sps_video_parameter_set_id = 0,
@@ -151,7 +182,6 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk
.pps_beta_offset_div2 = 0, .pps_beta_offset_div2 = 0,
.pps_tc_offset_div2 = 0, .pps_tc_offset_div2 = 0,
.log2_parallel_merge_level_minus2 = 0, .log2_parallel_merge_level_minus2 = 0,
.log2_max_transform_skip_block_size_minus2 = 0,
.diff_cu_chroma_qp_offset_depth = 0, .diff_cu_chroma_qp_offset_depth = 0,
.chroma_qp_offset_list_len_minus1 = 0, .chroma_qp_offset_list_len_minus1 = 0,
.cb_qp_offset_list = {}, .cb_qp_offset_list = {},
@@ -162,8 +192,8 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk
.pps_act_cb_qp_offset_plus5 = 0, .pps_act_cb_qp_offset_plus5 = 0,
.pps_act_cr_qp_offset_plus3 = 0, .pps_act_cr_qp_offset_plus3 = 0,
.pps_num_palette_predictor_initializers = 0, .pps_num_palette_predictor_initializers = 0,
.luma_bit_depth_entry_minus8 = 0, .luma_bit_depth_entry_minus8 = static_cast<uint8_t>(settings.bit_depth - 8),
.chroma_bit_depth_entry_minus8 = 0, .chroma_bit_depth_entry_minus8 = static_cast<uint8_t>(settings.bit_depth - 8),
.num_tile_columns_minus1 = 0, .num_tile_columns_minus1 = 0,
.num_tile_rows_minus1 = 0, .num_tile_rows_minus1 = 0,
.reserved1 = 0, .reserved1 = 0,
@@ -171,6 +201,8 @@ wivrn::video_encoder_vulkan_h265::video_encoder_vulkan_h265(wivrn_vk_bundle & vk
.column_width_minus1 = {}, .column_width_minus1 = {},
.row_height_minus1 = {}, .row_height_minus1 = {},
.reserved3 = 0, .reserved3 = 0,
.pScalingLists = nullptr,
.pPredictorPaletteEntries = nullptr,
} }
{ {
if (not std::ranges::any_of(vk.device_extensions, [](std::string_view ext) { return ext == VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME; })) if (not std::ranges::any_of(vk.device_extensions, [](std::string_view ext) { return ext == VK_KHR_VIDEO_ENCODE_H265_EXTENSION_NAME; }))
@@ -195,44 +227,79 @@ std::vector<void *> wivrn::video_encoder_vulkan_h265::setup_slot_info(size_t dpb
return res; return res;
} }
std::unique_ptr<wivrn::video_encoder_vulkan_h265> wivrn::video_encoder_vulkan_h265::create( static auto get_video_caps(vk::raii::PhysicalDevice & phys_dev, int bit_depth)
wivrn_vk_bundle & vk,
encoder_settings & settings,
float fps)
{ {
vk::Rect2D rect{ if (!(bit_depth == 8 || bit_depth == 10))
.offset = { throw std::runtime_error("h265 encoder supports 8-bit or 10-bit only");
.x = settings.offset_x,
.y = settings.offset_y, vk::StructureChain video_profile_info{
vk::VideoProfileInfoKHR{
.videoCodecOperation = vk::VideoCodecOperationFlagBitsKHR::eEncodeH265,
.chromaSubsampling = vk::VideoChromaSubsamplingFlagBitsKHR::e420,
.lumaBitDepth = bit_depth == 10 ? vk::VideoComponentBitDepthFlagBitsKHR::e10 : vk::VideoComponentBitDepthFlagBitsKHR::e8,
.chromaBitDepth = bit_depth == 10 ? vk::VideoComponentBitDepthFlagBitsKHR::e10 : vk::VideoComponentBitDepthFlagBitsKHR::e8,
}, },
.extent = { vk::VideoEncodeH265ProfileInfoKHR{
.width = settings.width, .stdProfileIdc = bit_depth == 10 ? STD_VIDEO_H265_PROFILE_IDC_MAIN_10 : STD_VIDEO_H265_PROFILE_IDC_MAIN,
.height = settings.height,
}, },
}; vk::VideoEncodeUsageInfoKHR{
.videoUsageHints = vk::VideoEncodeUsageFlagBitsKHR::eStreaming,
.videoContentHints = vk::VideoEncodeContentFlagBitsKHR::eRendered,
.tuningMode = vk::VideoEncodeTuningModeKHR::eUltraLowLatency,
}};
try
{
auto [video_caps, encode_caps, encode_h265_caps] =
phys_dev.getVideoCapabilitiesKHR<
vk::VideoCapabilitiesKHR,
vk::VideoEncodeCapabilitiesKHR,
vk::VideoEncodeH265CapabilitiesKHR>(video_profile_info.get());
return std::make_tuple(video_caps, encode_caps, encode_h265_caps, video_profile_info);
}
catch (...)
{}
// NVIDIA fails if the structure is there
video_profile_info.unlink<vk::VideoEncodeUsageInfoKHR>();
auto [video_caps, encode_caps, encode_h265_caps] = auto [video_caps, encode_caps, encode_h265_caps] =
vk.physical_device.getVideoCapabilitiesKHR< phys_dev.getVideoCapabilitiesKHR<
vk::VideoCapabilitiesKHR, vk::VideoCapabilitiesKHR,
vk::VideoEncodeCapabilitiesKHR, vk::VideoEncodeCapabilitiesKHR,
vk::VideoEncodeH265CapabilitiesKHR>(video_profile_info.get()); vk::VideoEncodeH265CapabilitiesKHR>(video_profile_info.get());
return std::make_tuple(video_caps, encode_caps, encode_h265_caps, video_profile_info);
}
std::unique_ptr<video_encoder_vulkan_h265> self(new video_encoder_vulkan_h265(vk, rect, encode_caps, fps, settings.bitrate)); std::unique_ptr<wivrn::video_encoder_vulkan_h265> wivrn::video_encoder_vulkan_h265::create(
wivrn_vk_bundle & vk,
encoder_settings & settings,
float fps,
uint8_t stream_idx)
{
vk::Rect2D rect{
.offset = {.x = settings.offset_x, .y = settings.offset_y},
.extent = {.width = settings.width, .height = settings.height},
};
vk::VideoEncodeH265SessionParametersAddInfoKHR h265_add_info{}; auto [video_caps, encode_caps, encode_h265_caps, video_profile_info] = get_video_caps(vk.physical_device, settings.bit_depth);
h265_add_info.setStdVPSs(self->vps);
h265_add_info.setStdSPSs(self->sps);
h265_add_info.setStdPPSs(self->pps);
vk::VideoEncodeH265SessionParametersCreateInfoKHR h265_session_params{ std::unique_ptr<video_encoder_vulkan_h265> self(
new video_encoder_vulkan_h265(vk, rect, video_caps, encode_caps, fps, stream_idx, settings));
vk::VideoEncodeH265SessionParametersAddInfoKHR add_info{};
add_info.setStdVPSs(self->vps);
add_info.setStdSPSs(self->sps);
add_info.setStdPPSs(self->pps);
vk::VideoEncodeH265SessionParametersCreateInfoKHR session_params_info{
.maxStdVPSCount = 1, .maxStdVPSCount = 1,
.maxStdSPSCount = 1, .maxStdSPSCount = 1,
.maxStdPPSCount = 1, .maxStdPPSCount = 1,
.pParametersAddInfo = &h265_add_info, .pParametersAddInfo = &add_info,
}; };
vk::VideoEncodeH265SessionCreateInfoKHR session_create_info{ vk::VideoEncodeH265SessionCreateInfoKHR session_create_info{
.useMaxLevelIdc = false, .useMaxLevelIdc = false, // let driver clamp if needed
}; };
if (encode_h265_caps.requiresGopRemainingFrames) if (encode_h265_caps.requiresGopRemainingFrames)
@@ -243,16 +310,39 @@ std::unique_ptr<wivrn::video_encoder_vulkan_h265> wivrn::video_encoder_vulkan_h2
.gopRemainingP = std::numeric_limits<uint32_t>::max(), .gopRemainingP = std::numeric_limits<uint32_t>::max(),
.gopRemainingB = 0, .gopRemainingB = 0,
}; };
self->rate_control_h265 = vk::VideoEncodeH265RateControlInfoKHR{ self->rc_h265 = vk::VideoEncodeH265RateControlInfoKHR{
.pNext = &self->gop_info, .pNext = &self->gop_info,
.gopFrameCount = std::numeric_limits<uint32_t>::max(), .flags = {},
.idrPeriod = std::numeric_limits<uint32_t>::max(),
}; };
self->rate_control->pNext = &self->rate_control_h265; self->rate_control->pNext = &self->rc_h265;
} }
self->init(video_caps, video_profile_info.get(), &session_create_info, &h265_session_params); self->sps.log2_diff_max_min_luma_coding_block_size = find_msb((uint32_t)encode_h265_caps.ctbSizes) + 1; // First bit is 16x16.
self->sps.log2_min_luma_transform_block_size_minus2 = find_lsb((uint32_t)encode_h265_caps.transformBlockSizes);
self->sps.log2_diff_max_min_luma_transform_block_size =
find_msb((uint32_t)encode_h265_caps.transformBlockSizes) - find_lsb((uint32_t)encode_h265_caps.transformBlockSizes);
uint32_t max_transform_hierarchy = (find_msb((uint32_t)encode_h265_caps.ctbSizes) + 4) - (find_lsb((uint32_t)encode_h265_caps.transformBlockSizes) + 2);
self->sps.max_transform_hierarchy_depth_inter = max_transform_hierarchy;
self->sps.max_transform_hierarchy_depth_intra = max_transform_hierarchy;
uint32_t syntax_flags = (uint32_t)encode_h265_caps.stdSyntaxFlags;
if ((syntax_flags & VK_VIDEO_ENCODE_H265_STD_TRANSFORM_SKIP_ENABLED_FLAG_SET_BIT_KHR) != 0 ||
(syntax_flags & VK_VIDEO_ENCODE_H265_STD_TRANSFORM_SKIP_ENABLED_FLAG_UNSET_BIT_KHR) == 0)
{
self->pps.flags.transform_skip_enabled_flag = 1;
self->pps.log2_max_transform_skip_block_size_minus2 = find_msb((uint32_t)encode_h265_caps.transformBlockSizes);
}
if ((syntax_flags & VK_VIDEO_ENCODE_H265_STD_CONSTRAINED_INTRA_PRED_FLAG_SET_BIT_KHR) != 0)
self->pps.flags.constrained_intra_pred_flag = 1;
if ((syntax_flags & VK_VIDEO_ENCODE_H265_STD_SAMPLE_ADAPTIVE_OFFSET_ENABLED_FLAG_SET_BIT_KHR) != 0)
self->sample_adaptive_offset_enabled = true;
self->rate_control_layer.pNext = &self->rc_layer_h265;
self->init(video_caps, video_profile_info.get(), &session_create_info, &session_params_info);
return self; return self;
} }
@@ -262,6 +352,9 @@ std::vector<uint8_t> wivrn::video_encoder_vulkan_h265::get_vps_sps_pps()
.writeStdVPS = true, .writeStdVPS = true,
.writeStdSPS = true, .writeStdSPS = true,
.writeStdPPS = true, .writeStdPPS = true,
.stdVPSId = 0,
.stdSPSId = 0,
.stdPPSId = 0,
}; };
return get_encoded_parameters(&next); return get_encoded_parameters(&next);
} }
@@ -269,50 +362,28 @@ std::vector<uint8_t> wivrn::video_encoder_vulkan_h265::get_vps_sps_pps()
void wivrn::video_encoder_vulkan_h265::send_idr_data() void wivrn::video_encoder_vulkan_h265::send_idr_data()
{ {
auto data = get_vps_sps_pps(); auto data = get_vps_sps_pps();
SendData(data, false); SendData(data, false, true);
} }
void * wivrn::video_encoder_vulkan_h265::encode_info_next(uint32_t frame_num, size_t slot, std::optional<size_t> ref) void * wivrn::video_encoder_vulkan_h265::encode_info_next(uint32_t frame_num, size_t slot, std::optional<int32_t> ref_slot)
{ {
slice_header = { slice_header = {
.flags = .flags = {
{ .first_slice_segment_in_pic_flag = 1,
.first_slice_segment_in_pic_flag = 0, .slice_sao_luma_flag = sample_adaptive_offset_enabled,
.dependent_slice_segment_flag = 0, .slice_sao_chroma_flag = sample_adaptive_offset_enabled,
.slice_sao_luma_flag = 0, .num_ref_idx_active_override_flag = ref_slot ? 1u : 0u,
.slice_sao_chroma_flag = 0, .collocated_from_l0_flag = 1,
.num_ref_idx_active_override_flag = 0, },
.mvd_l1_zero_flag = 0, .slice_type = ref_slot ? STD_VIDEO_H265_SLICE_TYPE_P : STD_VIDEO_H265_SLICE_TYPE_I,
.cabac_init_flag = 0, .MaxNumMergeCand = 5,
.cu_chroma_qp_offset_enabled_flag = 0,
.deblocking_filter_override_flag = 0,
.slice_deblocking_filter_disabled_flag = 0,
.collocated_from_l0_flag = 0,
.slice_loop_filter_across_slices_enabled_flag = 0,
},
.slice_type = ref ? STD_VIDEO_H265_SLICE_TYPE_P
: STD_VIDEO_H265_SLICE_TYPE_I,
.slice_segment_address = 0,
.collocated_ref_idx = 0,
.MaxNumMergeCand = 0,
.slice_cb_qp_offset = 0,
.slice_cr_qp_offset = 0,
.slice_beta_offset_div2 = 0,
.slice_tc_offset_div2 = 0,
.slice_act_y_qp_offset = 0,
.slice_act_cb_qp_offset = 0,
.slice_act_cr_qp_offset = 0,
.slice_qp_delta = 0,
}; };
nalu_slice_info = vk::VideoEncodeH265NaluSliceSegmentInfoKHR{ nalu_slice_info = vk::VideoEncodeH265NaluSliceSegmentInfoKHR{
.constantQp = 0,
.pStdSliceSegmentHeader = &slice_header, .pStdSliceSegmentHeader = &slice_header,
}; };
reference_lists_info = { reference_lists_info = {
.flags = .flags = {.ref_pic_list_modification_flag_l0 = 0, .ref_pic_list_modification_flag_l1 = 0},
{
.ref_pic_list_modification_flag_l0 = 0,
.ref_pic_list_modification_flag_l1 = 0,
},
.num_ref_idx_l0_active_minus1 = 0, .num_ref_idx_l0_active_minus1 = 0,
.num_ref_idx_l1_active_minus1 = 0, .num_ref_idx_l1_active_minus1 = 0,
.RefPicList0 = {}, .RefPicList0 = {},
@@ -320,92 +391,99 @@ void * wivrn::video_encoder_vulkan_h265::encode_info_next(uint32_t frame_num, si
.list_entry_l0 = {}, .list_entry_l0 = {},
.list_entry_l1 = {}, .list_entry_l1 = {},
}; };
std::fill(reference_lists_info.RefPicList0, std::ranges::fill(reference_lists_info.RefPicList0, STD_VIDEO_H265_NO_REFERENCE_PICTURE);
reference_lists_info.RefPicList0 + sizeof(reference_lists_info.RefPicList0), std::ranges::fill(reference_lists_info.RefPicList1, STD_VIDEO_H265_NO_REFERENCE_PICTURE);
STD_VIDEO_H265_NO_REFERENCE_PICTURE);
std::fill(reference_lists_info.RefPicList1, const int32_t poc = int32_t(frame_num);
reference_lists_info.RefPicList1 + sizeof(reference_lists_info.RefPicList1),
STD_VIDEO_H265_NO_REFERENCE_PICTURE); if (ref_slot)
if (ref)
{ {
reference_lists_info.RefPicList0[0] = *ref; const int32_t refPoc = dpb_std_info[*ref_slot].PicOrderCntVal;
st_rps = {};
for (uint32_t i = 0; i < poc_history.size(); ++i)
{
const uint32_t delta = uint32_t(poc - poc_history[i]) - i; // deltas are accumulative!
st_rps.delta_poc_s0_minus1[i] = uint16_t(delta - 1);
if (poc_history[i] == refPoc)
{
st_rps.used_by_curr_pic_s0_flag |= (1u << i);
st_rps.num_negative_pics = uint8_t(i + 1);
break;
}
}
st_rps.num_positive_pics = 0;
st_rps.used_by_curr_pic_flag = 0;
reference_lists_info.num_ref_idx_l0_active_minus1 = 0;
reference_lists_info.RefPicList0[0] = static_cast<uint8_t>(*ref_slot);
if (st_rps.used_by_curr_pic_s0_flag == 0)
{
// ref_slot is too old → encode an IDR instead
ref_slot.reset();
poc_history.clear();
}
}
else
{
poc_history.clear();
} }
std_picture_info = { std_picture_info = {
.flags = .flags = {
{ .is_reference = 1,
.is_reference = 1, .IrapPicFlag = ref_slot ? 0u : 1u,
.IrapPicFlag = uint32_t(ref ? 0 : 1), .used_for_long_term_reference = 0,
.used_for_long_term_reference = 0, .discardable_flag = 0,
.discardable_flag = 0, .cross_layer_bla_flag = 0,
.cross_layer_bla_flag = 0, .pic_output_flag = 1,
.pic_output_flag = 0, .no_output_of_prior_pics_flag = ref_slot ? 0u : 1u,
.no_output_of_prior_pics_flag = 0, .short_term_ref_pic_set_sps_flag = 0u,
.short_term_ref_pic_set_sps_flag = 0, .slice_temporal_mvp_enabled_flag = 1,
.slice_temporal_mvp_enabled_flag = 0, },
}, .pic_type = ref_slot ? STD_VIDEO_H265_PICTURE_TYPE_P : STD_VIDEO_H265_PICTURE_TYPE_IDR,
.pic_type = ref ? STD_VIDEO_H265_PICTURE_TYPE_P
: STD_VIDEO_H265_PICTURE_TYPE_IDR,
.sps_video_parameter_set_id = 0, .sps_video_parameter_set_id = 0,
.pps_seq_parameter_set_id = 0, .pps_seq_parameter_set_id = sps.sps_seq_parameter_set_id,
.pps_pic_parameter_set_id = 0, .pps_pic_parameter_set_id = pps.pps_pic_parameter_set_id,
.short_term_ref_pic_set_idx = 0, .short_term_ref_pic_set_idx = 0,
.PicOrderCntVal = 0, .PicOrderCntVal = int32_t(poc),
.TemporalId = 0, .TemporalId = 0,
.reserved1 = {},
.pRefLists = ref_slot ? &reference_lists_info : nullptr,
.pShortTermRefPicSet = ref_slot ? &st_rps : nullptr,
.pLongTermRefPics = nullptr,
}; };
picture_info = vk::VideoEncodeH265PictureInfoKHR{ picture_info = vk::VideoEncodeH265PictureInfoKHR{
.naluSliceSegmentEntryCount = 1, .naluSliceSegmentEntryCount = 1,
.pNaluSliceSegmentEntries = &nalu_slice_info, .pNaluSliceSegmentEntries = &nalu_slice_info,
.pStdPictureInfo = &std_picture_info, .pStdPictureInfo = &std_picture_info,
}; };
dpb_std_info[slot].pic_type = std_picture_info.pic_type; auto & i = dpb_std_info[slot];
i.flags = {.used_for_long_term_reference = 0, .unused_for_reference = 0};
i.pic_type = std_picture_info.pic_type;
i.PicOrderCntVal = std_picture_info.PicOrderCntVal;
i.TemporalId = std_picture_info.TemporalId;
if (not ref) const uint32_t history_limit = std::min<uint32_t>(16u, dpb.max_dec_pic_buffering_minus1[0]);
++idr_id;
if (poc_history.size() < 1 || poc_history.front() != poc)
poc_history.push_front(poc);
if (poc_history.size() > history_limit)
poc_history.pop_back();
return &picture_info; return &picture_info;
} }
vk::ExtensionProperties wivrn::video_encoder_vulkan_h265::std_header_version() vk::ExtensionProperties wivrn::video_encoder_vulkan_h265::std_header_version()
{ {
// FIXME: update to version 1.0
vk::ExtensionProperties std_header_version{ vk::ExtensionProperties std_header_version{
.specVersion = 0x0000900b, // VK_MAKE_VIDEO_STD_VERSION(1, 0, 0), .specVersion = VK_MAKE_VIDEO_STD_VERSION(1, 0, 0),
}; };
strcpy(std_header_version.extensionName, strcpy(std_header_version.extensionName,
VK_STD_VULKAN_VIDEO_CODEC_H265_ENCODE_EXTENSION_NAME); VK_STD_VULKAN_VIDEO_CODEC_H265_ENCODE_EXTENSION_NAME);
return std_header_version; return std_header_version;
} }
decltype(wivrn::video_encoder_vulkan_h265::video_profile_info) wivrn::video_encoder_vulkan_h265::video_profile_info = vk::StructureChain{
vk::VideoProfileInfoKHR{
.videoCodecOperation =
vk::VideoCodecOperationFlagBitsKHR::eEncodeH265,
.chromaSubsampling = vk::VideoChromaSubsamplingFlagBitsKHR::e420,
.lumaBitDepth = vk::VideoComponentBitDepthFlagBitsKHR::e8,
.chromaBitDepth = vk::VideoComponentBitDepthFlagBitsKHR::e8,
},
vk::VideoEncodeH265ProfileInfoKHR{
.stdProfileIdc = STD_VIDEO_H265_PROFILE_IDC_MAIN,
},
vk::VideoEncodeUsageInfoKHR{
.videoUsageHints = vk::VideoEncodeUsageFlagBitsKHR::eStreaming,
.videoContentHints = vk::VideoEncodeContentFlagBitsKHR::eRendered,
.tuningMode = vk::VideoEncodeTuningModeKHR::eUltraLowLatency,
}};
vk::StructureChain video_profile_info{
vk::VideoProfileInfoKHR{
.videoCodecOperation =
vk::VideoCodecOperationFlagBitsKHR::eEncodeH265,
.chromaSubsampling = vk::VideoChromaSubsamplingFlagBitsKHR::e420,
.lumaBitDepth = vk::VideoComponentBitDepthFlagBitsKHR::e8,
.chromaBitDepth = vk::VideoComponentBitDepthFlagBitsKHR::e8,
},
vk::VideoEncodeH265ProfileInfoKHR{
.stdProfileIdc = STD_VIDEO_H265_PROFILE_IDC_MAIN,
},
vk::VideoEncodeUsageInfoKHR{
.videoUsageHints = vk::VideoEncodeUsageFlagBitsKHR::eStreaming,
.videoContentHints = vk::VideoEncodeContentFlagBitsKHR::eRendered,
.tuningMode = vk::VideoEncodeTuningModeKHR::eUltraLowLatency,
}};
+33 -14
View File
@@ -19,6 +19,7 @@
#include "video_encoder_vulkan.h" #include "video_encoder_vulkan.h"
#include <deque>
#include <memory> #include <memory>
#include <vector> #include <vector>
@@ -26,33 +27,50 @@
namespace wivrn namespace wivrn
{ {
class video_encoder_vulkan_h265 : public video_encoder_vulkan class video_encoder_vulkan_h265 : public video_encoder_vulkan
{ {
uint16_t idr_id = 0; std::deque<int32_t> poc_history;
StdVideoH265VideoParameterSet vps; bool sample_adaptive_offset_enabled = false;
StdVideoH265SequenceParameterSet sps;
StdVideoH265PictureParameterSet pps;
StdVideoEncodeH265SliceSegmentHeader slice_header; StdVideoH265SequenceParameterSetVui vui{};
vk::VideoEncodeH265NaluSliceSegmentInfoKHR nalu_slice_info; StdVideoH265DecPicBufMgr dpb{};
StdVideoEncodeH265PictureInfo std_picture_info; StdVideoH265ProfileTierLevel ptl{};
vk::VideoEncodeH265PictureInfoKHR picture_info; StdVideoH265VideoParameterSet vps{};
StdVideoEncodeH265ReferenceListsInfo reference_lists_info; StdVideoH265SequenceParameterSet sps{};
StdVideoH265PictureParameterSet pps{};
StdVideoH265ShortTermRefPicSet st_rps{};
StdVideoEncodeH265SliceSegmentHeader slice_header{};
vk::VideoEncodeH265NaluSliceSegmentInfoKHR nalu_slice_info{};
StdVideoEncodeH265ReferenceListsInfo reference_lists_info{};
StdVideoEncodeH265PictureInfo std_picture_info{};
vk::VideoEncodeH265PictureInfoKHR picture_info{};
std::vector<StdVideoEncodeH265ReferenceInfo> dpb_std_info; std::vector<StdVideoEncodeH265ReferenceInfo> dpb_std_info;
std::vector<vk::VideoEncodeH265DpbSlotInfoKHR> dpb_std_slots; std::vector<vk::VideoEncodeH265DpbSlotInfoKHR> dpb_std_slots;
vk::VideoEncodeH265GopRemainingFrameInfoKHR gop_info; vk::VideoEncodeH265GopRemainingFrameInfoKHR gop_info{};
vk::VideoEncodeH265RateControlInfoKHR rate_control_h265; vk::VideoEncodeH265RateControlInfoKHR rc_h265{};
vk::VideoEncodeH265RateControlLayerInfoKHR rc_layer_h265{};
video_encoder_vulkan_h265(wivrn_vk_bundle & vk, vk::Rect2D rect, vk::VideoEncodeCapabilitiesKHR encode_caps, float fps, uint64_t bitrate); video_encoder_vulkan_h265(wivrn_vk_bundle & vk,
vk::Rect2D rect,
const vk::VideoCapabilitiesKHR & video_caps,
const vk::VideoEncodeCapabilitiesKHR & encode_caps,
float fps,
uint8_t stream_idx,
const encoder_settings & settings);
protected: protected:
std::vector<void *> setup_slot_info(size_t dpb_size) override; std::vector<void *> setup_slot_info(size_t dpb_size) override;
void * encode_info_next(uint32_t frame_num, size_t slot, std::optional<size_t> ref) override; void * encode_info_next(uint32_t frame_num, size_t slot, std::optional<int32_t> ref_slot) override;
virtual vk::ExtensionProperties std_header_version() override; virtual vk::ExtensionProperties std_header_version() override;
void send_idr_data() override; void send_idr_data() override;
@@ -60,7 +78,8 @@ protected:
public: public:
static std::unique_ptr<video_encoder_vulkan_h265> create(wivrn_vk_bundle & vk, static std::unique_ptr<video_encoder_vulkan_h265> create(wivrn_vk_bundle & vk,
encoder_settings & settings, encoder_settings & settings,
float fps); float fps,
uint8_t stream_idx);
std::vector<uint8_t> get_vps_sps_pps(); std::vector<uint8_t> get_vps_sps_pps();
+18 -7
View File
@@ -39,7 +39,7 @@ void video_encoder_x264::ProcessCb(x264_t * h, x264_nal_t * nal, void * opaque)
{ {
case NAL_SPS: case NAL_SPS:
case NAL_PPS: { case NAL_PPS: {
self->SendData(data, false); self->SendData(data, false, self->control);
break; break;
} }
case NAL_SLICE: case NAL_SLICE:
@@ -57,7 +57,7 @@ void video_encoder_x264::ProcessNal(pending_nal && nal)
if (nal.first_mb == next_mb) if (nal.first_mb == next_mb)
{ {
next_mb = nal.last_mb + 1; next_mb = nal.last_mb + 1;
SendData(nal.data, next_mb == num_mb); SendData(nal.data, next_mb == num_mb, control);
} }
else else
{ {
@@ -91,7 +91,7 @@ video_encoder_x264::video_encoder_x264(
encoder_settings & settings, encoder_settings & settings,
float fps, float fps,
uint8_t stream_idx) : uint8_t stream_idx) :
video_encoder(stream_idx, settings.channels, settings.bitrate_multiplier, false) video_encoder(stream_idx, settings.channels, std::make_unique<default_idr_handler>(), settings.bitrate_multiplier, false)
{ {
if (settings.bit_depth != 8) if (settings.bit_depth != 8)
throw std::runtime_error("x264 encoder only supports 8-bit encoding"); throw std::runtime_error("x264 encoder only supports 8-bit encoding");
@@ -239,7 +239,7 @@ std::pair<bool, vk::Semaphore> video_encoder_x264::present_image(vk::Image y_cbc
return {false, nullptr}; return {false, nullptr};
} }
std::optional<video_encoder::data> video_encoder_x264::encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) std::optional<video_encoder::data> video_encoder_x264::encode(uint8_t slot, uint64_t frame_index)
{ {
bool reconfigure = false; bool reconfigure = false;
if (auto framerate = pending_framerate.exchange(0)) if (auto framerate = pending_framerate.exchange(0))
@@ -256,16 +256,27 @@ std::optional<video_encoder::data> video_encoder_x264::encode(bool idr, std::chr
param.rc.i_vbv_buffer_size = param.rc.i_bitrate / fps_mul * 1.1; param.rc.i_vbv_buffer_size = param.rc.i_bitrate / fps_mul * 1.1;
param.rc.i_vbv_max_bitrate = param.rc.i_bitrate; param.rc.i_vbv_max_bitrate = param.rc.i_bitrate;
} }
auto & idr_handler = ((default_idr_handler &)*idr);
if (reconfigure) if (reconfigure)
{ {
x264_encoder_reconfig(enc, &param); x264_encoder_reconfig(enc, &param);
idr = true; idr->reset();
} }
auto frame_type = idr_handler.get_type(frame_index);
int num_nal; int num_nal;
x264_nal_t * nal; x264_nal_t * nal;
auto & pic = in[slot].pic; auto & pic = in[slot].pic;
pic.i_type = idr ? X264_TYPE_IDR : X264_TYPE_P; switch (frame_type)
pic.i_pts = pts.time_since_epoch().count(); {
case default_idr_handler::frame_type::i:
control = true;
pic.i_type = X264_TYPE_IDR;
break;
case default_idr_handler::frame_type::p:
control = false;
pic.i_type = X264_TYPE_P;
break;
}
next_mb = 0; next_mb = 0;
assert(pending_nals.empty()); assert(pending_nals.empty());
int size = x264_encoder_encode(enc, &nal, &num_nal, &pic, &pic_out); int size = x264_encoder_encode(enc, &nal, &num_nal, &pic, &pic_out);
+2 -1
View File
@@ -34,6 +34,7 @@ class video_encoder_x264 : public video_encoder
{ {
x264_param_t param = {}; x264_param_t param = {};
x264_t * enc; x264_t * enc;
bool control;
x264_picture_t pic_out = {}; x264_picture_t pic_out = {};
@@ -65,7 +66,7 @@ public:
std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override; std::pair<bool, vk::Semaphore> present_image(vk::Image y_cbcr, vk::raii::CommandBuffer & cmd_buf, uint8_t slot, uint64_t frame_index) override;
std::optional<data> encode(bool idr, std::chrono::steady_clock::time_point pts, uint8_t slot) override; std::optional<data> encode(uint8_t slot, uint64_t frame_index) override;
~video_encoder_x264(); ~video_encoder_x264();