ACMX 2.139.0
Dual-Backend Real-Time GPU Video Synthesis
Loading...
Searching...
No Matches
ACMXVK/main_window.cpp
Go to the documentation of this file.
1#include "main_window.hpp"
2
3#include <csignal>
4
5namespace acmxvk {
6 namespace {
7 volatile std::sig_atomic_t HEADLESS_SHUTDOWN_REQUESTED = 0;
8 constexpr int COLOR_TRANSFER_SMPTE2084 = 16;
9 constexpr int COLOR_TRANSFER_ARIB_STD_B67 = 18;
10
11 [[nodiscard]] std::string format_bitrate(std::uint64_t bytes_written, double duration_seconds) {
12 if (duration_seconds <= 0.0 || !std::isfinite(duration_seconds)) {
13 return {};
14 }
15 const double bitrate_kbits = (static_cast<double>(bytes_written) * 8.0) / duration_seconds / 1000.0;
16 std::ostringstream text;
17 text << std::fixed << std::setprecision(1) << bitrate_kbits << " kbits/s";
18 return text.str();
19 }
20
21 [[nodiscard]] float decode_pq(float encoded) {
22 constexpr float M1 = 2610.0F / 16384.0F;
23 constexpr float M2 = 2523.0F / 32.0F;
24 constexpr float C1 = 3424.0F / 4096.0F;
25 constexpr float C2 = 2413.0F / 128.0F;
26 constexpr float C3 = 2392.0F / 128.0F;
27 const float power_value = std::pow(std::clamp(encoded, 0.0F, 1.0F), 1.0F / M2);
28 const float numerator = std::max(power_value - C1, 0.0F);
29 const float denominator = std::max(C2 - C3 * power_value, 1.0e-6F);
30 return std::pow(numerator / denominator, 1.0F / M1);
31 }
32
33 [[nodiscard]] float decode_hlg(float encoded) {
34 constexpr float A = 0.17883277F;
35 constexpr float B = 0.28466892F;
36 constexpr float C = 0.55991073F;
37 encoded = std::max(encoded, 0.0F);
38 if (encoded <= 0.5F) {
39 return encoded * encoded / 3.0F;
40 }
41 return (std::exp((encoded - C) / A) + B) / 12.0F;
42 }
43
44 [[nodiscard]] cv::Mat decode_hdr_transfer(const cv::Mat &rgba, bool hlg) {
45 if (rgba.empty() || (rgba.type() != CV_8UC4 && rgba.type() != CV_16UC4)) {
46 return rgba;
47 }
48 cv::Mat linear(rgba.rows, rgba.cols, CV_16UC4);
49 const float scale = rgba.type() == CV_16UC4 ? 1.0F / 65535.0F : 1.0F / 255.0F;
50 for (int row = 0; row < rgba.rows; ++row) {
51 auto *destination = linear.ptr<std::uint16_t>(row);
52 for (int column = 0; column < rgba.cols; ++column) {
53 for (int channel = 0; channel < 3; ++channel) {
54 const std::size_t offset = static_cast<std::size_t>(column) * 4U + static_cast<std::size_t>(channel);
55 const float encoded = rgba.type() == CV_16UC4 ? static_cast<float>(rgba.ptr<std::uint16_t>(row)[offset]) * scale : static_cast<float>(rgba.ptr<std::uint8_t>(row)[offset]) * scale;
56 const float decoded = hlg ? decode_hlg(encoded) : decode_pq(encoded);
57 destination[offset] = static_cast<std::uint16_t>(std::lround(std::clamp(decoded, 0.0F, 1.0F) * 65535.0F));
58 }
59 const std::size_t alpha_offset = static_cast<std::size_t>(column) * 4U + 3U;
60 destination[alpha_offset] = rgba.type() == CV_16UC4 ? rgba.ptr<std::uint16_t>(row)[alpha_offset] : static_cast<std::uint16_t>(rgba.ptr<std::uint8_t>(row)[alpha_offset] * 257U);
61 }
62 }
63 return linear;
64 }
65
66 [[nodiscard]] cv::Mat rgba16ToRgba8(const cv::Mat &rgba) {
67 if (rgba.empty() || rgba.type() != CV_16UC4) {
68 return rgba;
69 }
70 cv::Mat converted;
71 rgba.convertTo(converted, CV_8UC4, 1.0 / 257.0);
72 return converted;
73 }
74
75 [[nodiscard]] float tone_map_channel(float value) {
76 value = std::max(value, 0.0F);
77 return std::clamp((value * (2.51F * value + 0.03F)) / (value * (2.43F * value + 0.59F) + 0.14F), 0.0F, 1.0F);
78 }
79
80 [[nodiscard]] float encode_srgb(float value) {
81 value = std::clamp(value, 0.0F, 1.0F);
82 return value <= 0.0031308F ? 12.92F * value : 1.055F * std::pow(value, 1.0F / 2.4F) - 0.055F;
83 }
84
85 [[nodiscard]] std::vector<std::uint8_t> tone_map_hdr_rgba16(const std::vector<std::uint16_t> &rgba, bool hlg) {
86 std::vector<std::uint8_t> converted(rgba.size());
87 const float reference_scale = hlg ? 1000.0F / 203.0F : 10000.0F / 203.0F;
88 for (std::size_t offset = 0; offset + 3U < rgba.size(); offset += 4U) {
89 const auto decode = [hlg](std::uint16_t sample) {
90 const float encoded = static_cast<float>(sample) / 65535.0F;
91 return hlg ? decode_hlg(encoded) : decode_pq(encoded);
92 };
93 const float red = decode(rgba[offset]) * reference_scale;
94 const float green = decode(rgba[offset + 1U]) * reference_scale;
95 const float blue = decode(rgba[offset + 2U]) * reference_scale;
96 const float bt709_red = 1.660491F * red - 0.587641F * green - 0.072850F * blue;
97 const float bt709_green = -0.124550F * red + 1.132900F * green - 0.008349F * blue;
98 const float bt709_blue = -0.018151F * red - 0.100579F * green + 1.118730F * blue;
99 converted[offset] = static_cast<std::uint8_t>(std::lround(encode_srgb(tone_map_channel(bt709_red)) * 255.0F));
100 converted[offset + 1U] = static_cast<std::uint8_t>(std::lround(encode_srgb(tone_map_channel(bt709_green)) * 255.0F));
101 converted[offset + 2U] = static_cast<std::uint8_t>(std::lround(encode_srgb(tone_map_channel(bt709_blue)) * 255.0F));
102 converted[offset + 3U] = static_cast<std::uint8_t>((static_cast<std::uint32_t>(rgba[offset + 3U]) + 128U) / 257U);
103 }
104 return converted;
105 }
106 } // namespace
107
108 void request_headless_shutdown([[maybe_unused]] int signal_number) noexcept { HEADLESS_SHUTDOWN_REQUESTED = 1; }
109
110 // Window construction, event handling, rendering callbacks, and main loop.
111 MainWindow::MainWindow(Options options) : mxvk::VK_Window("ACMXVK", options.width, options.height, options.fullscreen, MXVK_VALIDATION, options.enable_vsync ? PresentModePreference::Vsync : PresentModePreference::LowLatency, options.headless ? RuntimeMode::Headless : RuntimeMode::Windowed), options(std::move(options)) {
112 if (this->options.headless) {
113 std::cout << "acmxvk: headless mode enabled: surface-free Vulkan "
114 "rendering without an SDL window\n";
115 }
116 setClearColor(0.0F, 0.0F, 0.0F, 1.0F);
117 setEnableScreenshot(this->options.enable_screenshot);
122 openAudio();
123 if (this->options.enable_audio_time) {
124#ifdef AUDIO_ENABLED
125 if (audioSourceOpen()) {
126 audio_time_active = true;
127 std::cout << "acmxvk: audio-reactive shader time enabled at "
128 "startup (--audio-time)\n";
129 } else {
130 std::cerr << "acmxvk: --audio-time requested but no audio source "
131 "is active; shader time remains on its normal clock\n";
132 }
133#endif
134 }
135 loadShaders();
139 openMidi();
140 loadPlaylist();
142 if (this->options.enable_random_autopilot) {
143 toggleAutopilot(false);
144 }
145 openInput();
151 openOutput();
152 updateWindowTitle(true);
153 }
154
159 try {
160 flushFrameReadbacks();
161 } catch (const std::exception &error) {
162 std::cerr << "acmxvk: unable to flush pending frame readbacks: " << error.what() << '\n';
163 }
166 }
167 if (model_initialized && getDevice() != VK_NULL_HANDLE) {
168 vkDeviceWaitIdle(getDevice());
169 input_model.cleanup(this);
170 model_initialized = false;
171 std::cout << "acmxvk: released 3D model resources\n";
172 }
173 const bool should_copy_audio = options.copy_audio && !options.mute_output && writer.is_open();
174#ifdef AUDIO_ENABLED
175 const bool should_mux_file_audio = file_audio_source != nullptr && writer.is_open() && !options.output_file.empty() && !options.png_output && !options.mute_output && output_frame_count > 0;
176 const bool should_mux_live_audio = audio_engine != nullptr && file_audio_source == nullptr && audio_engine->is_recording() && writer.is_open() && !options.output_file.empty() && !options.png_output && !options.copy_audio && !options.mute_output && output_frame_count > 0;
177 const bool should_write_live_audio = audio_engine != nullptr && audio_engine->is_recording() && !options.record_audio_file.empty();
178 audio::AudioRecording live_audio_recording;
179 if (audio_engine != nullptr && audio_engine->is_recording()) {
180 live_audio_recording = audio_engine->stop_recording();
181 }
182 if (file_audio_source != nullptr) {
183 file_audio_source->stop_output();
184 }
185#endif
186 if (writer.is_open()) {
187 writer.close();
188 std::cout << "acmxvk: recording closed after " << output_frame_count << " rendered frames";
190 std::cout << " (" << gap_fill_duplicate_count << " held-frame duplicates added)";
191 }
192 std::cout << '\n';
193 }
194 if (options.png_output) {
195 std::cout << "acmxvk: PNG sequence closed after " << png_frame_count << " frames\n";
196 }
197 if (options.generate_interval > 0) {
198 std::cout << "acmxvk: generated " << generated_frame_count << " periodic PNG frames\n";
199 }
200 if (capture.is_open()) {
201 capture.close();
202 }
203#ifdef MXVK_WITH_FFMPEG_CAPTURE
204 if (ffmpeg_capture.is_open()) {
205 ffmpeg_capture.close();
206 }
207#endif
208 if (should_copy_audio) {
210 std::cout << "acmxvk: copied audio track from " << options.input_file << " to " << options.output_file << '\n';
211 }
212#ifdef AUDIO_ENABLED
213 if (should_mux_file_audio) {
214 const double video_duration = writer.get_duration();
215 if (!file_audio_source->mux_into_video(options.output_file, video_duration)) {
216 std::cerr << "acmxvk: file-audio mux failed; preserving the "
217 "encoded video without audio\n";
218 }
219 }
220 if (should_write_live_audio) {
221 if (live_audio_recording.empty()) {
222 std::cerr << "acmxvk: standalone audio recording was empty; "
223 "no WAV file was written\n";
224 } else if (!audio::write_wav_file(live_audio_recording, options.record_audio_file)) {
225 std::cerr << "acmxvk: could not write WAV recording: " << options.record_audio_file << '\n';
226 } else {
227 std::cout << "acmxvk: wrote " << live_audio_recording.duration_seconds() << " seconds of microphone audio to " << options.record_audio_file << '\n';
228 }
229 }
230 if (should_mux_live_audio) {
231 const double video_duration = writer.get_duration();
232 if (live_audio_recording.empty()) {
233 std::cerr << "acmxvk: live audio recording was empty; preserving "
234 "the encoded video without audio\n";
235 } else if (!audio::FileAudioSource::mux_recording_into_video(std::move(live_audio_recording.samples), live_audio_recording.sample_rate, options.output_file, video_duration)) {
236 std::cerr << "acmxvk: live-audio mux failed; preserving the "
237 "encoded video without audio\n";
238 }
239 }
240#endif
242 }
243
244 void MainWindow::event(SDL_Event &event) {
245 mxvk::VK_Window::event(event);
246 if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_PAGEUP) {
247 adjustTimeSpeed(0.1);
248 } else if (event.type == SDL_EVENT_KEY_DOWN && event.key.key == SDLK_PAGEDOWN) {
249 adjustTimeSpeed(-0.1);
250 }
251
252 if (event.type == SDL_EVENT_KEY_DOWN && !event.key.repeat) {
253 switch (event.key.key) {
254 case SDLK_UP:
255 if ((event.key.mod & SDL_KMOD_SHIFT) != 0 || !playlist_enabled) {
256 selectShader(-1);
257 } else {
259 }
260 break;
261 case SDLK_DOWN:
262 if ((event.key.mod & SDL_KMOD_SHIFT) != 0 || !playlist_enabled) {
263 selectShader(1);
264 } else {
266 }
267 break;
268 case SDLK_LEFT:
269 selectGpuFilter(-1);
270 break;
271 case SDLK_RIGHT:
273 break;
274 case SDLK_SPACE:
278 std::cout << "acmxvk: shader effects " << (effects_enabled ? "enabled" : "bypassed") << '\n';
279 break;
280 case SDLK_P:
281 if (!playlist.empty()) {
285 std::cout << "acmxvk: playlist " << (playlist_enabled ? "enabled" : "disabled") << '\n';
286 if (playlist_enabled) {
287 logSelectedPlaylistNode("selected");
288 }
289 } else {
290 togglePause();
291 }
292 break;
293 case SDLK_L:
294 toggleFreeze();
295 break;
296 case SDLK_T:
298 previous_frame = std::chrono::steady_clock::now();
299 std::cout << "acmxvk: shader time " << (shader_time_active ? "enabled" : "disabled") << '\n';
300 break;
301 case SDLK_Q:
302#ifdef AUDIO_ENABLED
303 if (audioSourceOpen()) {
305 previous_frame = std::chrono::steady_clock::now();
306 std::cout << "acmxvk: audio-reactive shader time " << (audio_time_active ? "enabled" : "disabled") << '\n';
307 }
308#endif
309 break;
310 case SDLK_HOME:
311#ifdef AUDIO_ENABLED
312 if (audioSourceOpen()) {
314 std::cout << "acmxvk: audio delta-time scaling " << (audio_delta_time ? "enabled" : "disabled") << '\n';
315 }
316#endif
317 break;
318 case SDLK_END:
319#ifdef AUDIO_ENABLED
320 if (audioSourceOpen()) {
322 std::cout << "acmxvk: spectrum sensitivity scaling " << (spectrum_scale_by_sensitivity ? "enabled" : "disabled") << '\n';
323 }
324#endif
325 break;
326 case SDLK_U:
327 stepShaderTime(0.05);
328 break;
329 case SDLK_I:
330 stepShaderTime(-0.05);
331 break;
332 case SDLK_F:
334 break;
335 case SDLK_F9:
338 hud_fps_last_tick = std::chrono::steady_clock::now();
339 if (!counter_disabled) {
341 }
342 std::cout << "acmxvk: runtime HUD " << (counter_disabled ? "hidden" : "shown") << " (F9)\n";
343 break;
344 case SDLK_E:
345 if (!options.watermark_text.empty()) {
347 std::cout << "acmxvk: watermark " << (watermark_enabled ? "enabled" : "disabled") << '\n';
348 }
349 break;
350 case SDLK_INSERT:
352 break;
353 case SDLK_DELETE:
355 break;
356 case SDLK_M:
357 if (!configured_passes.empty()) {
361 std::cout << "acmxvk: multipass " << (multipass_enabled ? "enabled" : "disabled") << '\n';
362 }
363 break;
364 case SDLK_J:
365 toggleAutopilot(false);
366 break;
367 case SDLK_N:
369 std::cout << "acmxvk: random autopilot crossfade " << (autopilot_random_crossfade ? "enabled" : "disabled") << '\n';
370 break;
371 case SDLK_K:
373 std::cout << "acmxvk: shader lock " << (shader_locked ? "enabled" : "disabled") << '\n';
374 break;
375 case SDLK_3:
376 if (model_initialized) {
379 model_last_render_time = std::chrono::steady_clock::now();
381 std::cout << "acmxvk: " << (model_3d_active ? "3D model" : "2D sprite") << " rendering enabled\n";
382 }
383 break;
384 case SDLK_V:
385 if (model_initialized) {
387 std::cout << "acmxvk: 3D view rotation " << (model_auto_rotate ? "enabled" : "disabled") << '\n';
388 }
389 break;
390 case SDLK_C:
391 if (model_initialized) {
393 std::cout << "acmxvk: 3D wave effect " << (model_wave_active ? "enabled" : "disabled") << '\n';
394 }
395 break;
396 case SDLK_O:
397 if (model_initialized) {
399 std::cout << "acmxvk: 3D scale oscillation " << (model_scale_oscillation_active ? "enabled" : "disabled") << '\n';
400 }
401 break;
402 case SDLK_X:
403 if (model_initialized) {
404 model_pitch_degrees = 0.0F;
405 model_yaw_degrees = 270.0F;
410 model_scale = 1.0F;
412 std::cout << "acmxvk: model view reset\n";
413 }
414 break;
415 case SDLK_LEFTBRACKET:
416 cycleCrossfade(-1);
417 break;
418 case SDLK_RIGHTBRACKET:
420 break;
421 case SDLK_MINUS:
422 case SDLK_UNDERSCORE:
423 case SDLK_KP_MINUS:
424 if ((event.key.mod & SDL_KMOD_SHIFT) != 0) {
425 adjustModelScale(-0.05F);
426 }
427 break;
428 case SDLK_PLUS:
429 case SDLK_EQUALS:
430 case SDLK_KP_PLUS:
431 if ((event.key.mod & SDL_KMOD_SHIFT) != 0) {
432 adjustModelScale(0.05F);
433 }
434 break;
435 case SDLK_COMMA:
436 if (model_initialized) {
437 model_rotation_speed = std::max(0.0F, model_rotation_speed - 5.0F);
438 std::cout << "acmxvk: 3D view rotation speed " << model_rotation_speed << " degrees/second\n";
439 }
440 break;
441 case SDLK_PERIOD:
442 if (model_initialized) {
443 model_rotation_speed = std::min(360.0F, model_rotation_speed + 5.0F);
444 std::cout << "acmxvk: 3D view rotation speed " << model_rotation_speed << " degrees/second\n";
445 }
446 break;
447 case SDLK_Y:
448 toggleAutopilot(true);
449 break;
450 case SDLK_Z:
452 break;
453 case SDLK_4:
455 break;
456 case SDLK_5:
458 break;
459 case SDLK_6:
461 break;
462 default:
463 break;
464 }
465 } else if (event.type == SDL_EVENT_MOUSE_MOTION) {
466 mouse_x = event.motion.x;
467 mouse_y = event.motion.y;
469 const int x = static_cast<int>(event.motion.x);
470 const int y = static_cast<int>(event.motion.y);
471 model_yaw_degrees += static_cast<float>(x - model_last_mouse_x) * 0.35F;
472 model_pitch_degrees = std::clamp(model_pitch_degrees + static_cast<float>(y - model_last_mouse_y) * 0.35F, -89.0F, 89.0F);
475 }
476 } else if (event.type == SDL_EVENT_MOUSE_BUTTON_DOWN && event.button.button == SDL_BUTTON_LEFT) {
477 mouse_pressed = true;
478 mouse_x = event.button.x;
479 mouse_y = event.button.y;
481 model_last_mouse_x = static_cast<int>(event.button.x);
482 model_last_mouse_y = static_cast<int>(event.button.y);
483 } else if (event.type == SDL_EVENT_MOUSE_BUTTON_UP && event.button.button == SDL_BUTTON_LEFT) {
484 mouse_pressed = false;
485 model_mouse_dragging = false;
486 mouse_x = event.button.x;
487 mouse_y = event.button.y;
488 } else if (event.type == SDL_EVENT_MOUSE_WHEEL && model_initialized && !model_scale_oscillation_active) {
489 const float wheel = event.wheel.y != 0.0F ? event.wheel.y : static_cast<float>(event.wheel.integer_y);
490 model_camera_distance = std::clamp(model_camera_distance - wheel * 0.2F, -20.0F, 20.0F);
491 }
492 }
493
495 // Initial headless extent configuration creates MXVK's surface-free
496 // targets before MainWindow performs its normal sprite setup. Do not
497 // initialize here: doing so consumes video frame zero, after which the
498 // constructor consumes frame one and leaves an empty encoded PTS zero.
499 if (frame_sprite == nullptr) {
500 return;
501 }
503 if (model_initialized) {
504 input_model.resize(this);
505 }
507 }
508
509 void MainWindow::onRecordCustomRendering(VkCommandBuffer command_buffer, std::uint32_t image_index) {
511 return;
512 }
513 recordModel(command_buffer, image_index, VK_NULL_HANDLE);
514 }
515
516 void MainWindow::onRecordPostProcessingTexture(VkCommandBuffer command_buffer, std::uint32_t image_index, VkImageView texture_view, [[maybe_unused]] VkExtent2D texture_extent) {
518 return;
519 }
520 recordModel(command_buffer, image_index, texture_view);
521 }
522
523 void MainWindow::recordModel(VkCommandBuffer command_buffer, std::uint32_t image_index, VkImageView texture_view) {
525 return;
526 }
527
528 const auto now = std::chrono::steady_clock::now();
529 float delta = std::chrono::duration<float>(now - model_last_render_time).count();
531 delta = std::clamp(delta, 0.0F, 0.1F);
532
533 float animation_delta = delta;
534 std::uint64_t animation_steps = 1U;
535 double video_timeline = 0.0;
536 std::uint64_t video_frame_index = 0U;
537 if (currentVideoTimeline(video_timeline, &video_frame_index)) {
540 model_wave_phase = 0.0F;
548 if (model_auto_rotate) {
550 }
551 }
552 animation_delta = 0.0F;
553 animation_steps = 0U;
555 } else {
556 animation_steps = video_frame_index - previous_model_video_frame;
557 animation_delta = static_cast<float>(static_cast<double>(animation_steps) / video_source_fps);
558 }
559 previous_model_video_frame = video_frame_index;
560 } else {
562 }
565 }
566 if (model_wave_active) {
567 const float wave_step = audio_time_active && audioSourceOpen() ? model_wave_audio_step : 0.05F;
568 model_wave_phase = std::fmod(model_wave_phase + wave_step * static_cast<float>(animation_steps), 360.0F);
569
570 const auto advance_amplitude = [](float &amplitude, float &direction, std::uint64_t steps) {
571 constexpr float AMPLITUDE_RANGE = 0.5F;
572 constexpr float AMPLITUDE_PERIOD = AMPLITUDE_RANGE * 2.0F;
573 float phase = direction >= 0.0F ? amplitude : AMPLITUDE_PERIOD - amplitude;
574 phase = std::fmod(phase + 0.005F * static_cast<float>(steps), AMPLITUDE_PERIOD);
575 if (phase < AMPLITUDE_RANGE) {
576 amplitude = phase;
577 direction = 1.0F;
578 } else {
579 amplitude = AMPLITUDE_PERIOD - phase;
580 direction = -1.0F;
581 }
582 };
583 advance_amplitude(model_wave_amplitude_x, model_wave_direction_x, animation_steps);
584 advance_amplitude(model_wave_amplitude_y, model_wave_direction_y, animation_steps);
585 advance_amplitude(model_wave_amplitude_z, model_wave_direction_z, animation_steps);
586 }
588 model_scale_oscillation_phase = std::fmod(model_scale_oscillation_phase + 0.016F * static_cast<float>(animation_steps), 2.0F * std::numbers::pi_v<float>);
589 }
590
591 const bool *keyboard = SDL_GetKeyboardState(nullptr);
592 const bool model_scale_modifier = (SDL_GetModState() & SDL_KMOD_SHIFT) != 0;
593 if (!model_scale_oscillation_active && keyboard[SDL_SCANCODE_1]) {
594 model_camera_movement_speed = std::clamp(model_camera_movement_speed + 0.1F * delta * 30.0F, 0.01F, 20.0F);
595 }
596 if (!model_scale_oscillation_active && keyboard[SDL_SCANCODE_2]) {
597 model_camera_movement_speed = std::clamp(model_camera_movement_speed - 0.1F * delta * 30.0F, 0.01F, 20.0F);
598 }
599 if (!model_scale_oscillation_active && !model_scale_modifier && (keyboard[SDL_SCANCODE_EQUALS] || keyboard[SDL_SCANCODE_KP_PLUS])) {
600 model_camera_distance = std::clamp(model_camera_distance + model_camera_movement_speed * delta, -20.0F, 20.0F);
601 }
602 if (!model_scale_oscillation_active && !model_scale_modifier && (keyboard[SDL_SCANCODE_MINUS] || keyboard[SDL_SCANCODE_KP_MINUS])) {
603 model_camera_distance = std::clamp(model_camera_distance - model_camera_movement_speed * delta, -20.0F, 20.0F);
604 }
605 if (!model_auto_rotate) {
606 if (keyboard[SDL_SCANCODE_W]) {
607 model_pitch_degrees += model_camera_rotation_speed * 0.3F * delta * 30.0F;
608 }
609 if (keyboard[SDL_SCANCODE_S]) {
610 model_pitch_degrees -= model_camera_rotation_speed * 0.33F * delta * 30.0F;
611 }
612 model_pitch_degrees = std::fmod(model_pitch_degrees, 360.0F);
613 if (model_pitch_degrees < 0.0F) {
614 model_pitch_degrees += 360.0F;
615 }
616 if (keyboard[SDL_SCANCODE_A]) {
617 model_yaw_degrees -= model_camera_rotation_speed * 0.3F * delta * 30.0F;
618 }
619 if (keyboard[SDL_SCANCODE_D]) {
620 model_yaw_degrees += model_camera_rotation_speed * 0.3F * delta * 30.0F;
621 }
622 model_yaw_degrees = std::fmod(model_yaw_degrees, 360.0F);
623 if (model_yaw_degrees < 0.0F) {
624 model_yaw_degrees += 360.0F;
625 }
626 }
627
628 const VkExtent2D extent = getRenderExtent();
629 const float aspect = extent.height > 0U ? static_cast<float>(extent.width) / static_cast<float>(extent.height) : 1.0F;
630
631 mxvk::UniformBufferObject uniforms{};
632 uniforms.model = glm::scale(glm::mat4(1.0F), glm::vec3(input_model.modelRenderScale() * model_scale));
633 uniforms.model = glm::rotate(uniforms.model, glm::radians(model_rotation_x_degrees), glm::vec3(1.0F, 0.0F, 0.0F));
634 uniforms.model = glm::rotate(uniforms.model, glm::radians(model_rotation_y_degrees), glm::vec3(0.0F, 1.0F, 0.0F));
635 uniforms.model = glm::rotate(uniforms.model, glm::radians(model_rotation_z_degrees), glm::vec3(0.0F, 0.0F, 1.0F));
636 uniforms.model = glm::translate(uniforms.model, input_model.modelCenterOffset());
637
638 glm::vec3 look_direction{};
639 glm::vec3 camera_up(0.0F, 1.0F, 0.0F);
640 if (model_auto_rotate) {
641 const float rotation = glm::radians(model_view_rotation_degrees);
642 look_direction = glm::vec3(0.48F * std::sin(rotation), 0.48F * std::sin(rotation * 0.7F), 0.48F * std::cos(rotation));
643 } else {
644 const float pitch = glm::radians(model_pitch_degrees);
645 const float yaw = glm::radians(model_yaw_degrees);
646 look_direction = glm::normalize(glm::vec3(std::cos(pitch) * std::cos(yaw), std::sin(pitch), std::cos(pitch) * std::sin(yaw))) * 0.48F;
647 camera_up = glm::vec3(-std::sin(pitch) * std::cos(yaw), std::cos(pitch), -std::sin(pitch) * std::sin(yaw));
648 }
649 const float camera_offset = model_scale_oscillation_active ? 0.3F * std::sin(model_scale_oscillation_phase) : model_camera_distance;
650 const glm::vec3 camera_position = -glm::normalize(look_direction) * camera_offset;
651 uniforms.view = glm::lookAt(camera_position, camera_position + look_direction, camera_up);
652 uniforms.proj = glm::perspective(glm::radians(120.0F), aspect, 0.01F, 1000.0F);
653 uniforms.proj[1][1] *= -1.0F;
655
656 input_model.updateFragmentUBO(image_index, model_fragment_uniforms);
657
658 mxvk::ModelFragmentPushConstants fragment_constants{};
659 fragment_constants.screenWidth = static_cast<float>(extent.width);
660 fragment_constants.screenHeight = static_cast<float>(extent.height);
661 fragment_constants.spriteSizeW = static_cast<float>(extent.width);
662 fragment_constants.spriteSizeH = static_cast<float>(extent.height);
663 fragment_constants.effectsOn = effects_enabled ? 1.0F : 0.0F;
664 fragment_constants.params = glm::vec4(1.0F, 1.0F, 1.0F, static_cast<float>(shader_time));
665 input_model.setFragmentPushConstants(fragment_constants);
666
667 if (texture_view != VK_NULL_HANDLE) {
668 input_model.renderWithExternalTexture(command_buffer, image_index, texture_view, uniforms, false);
669 } else {
670 input_model.renderWithPushConstants(command_buffer, image_index, 0U, uniforms, false);
671 }
672 }
673
675 if (HEADLESS_SHUTDOWN_REQUESTED != 0) {
677 std::cout << "acmxvk: shutdown requested; draining rendered "
678 "frames and closing output\n";
680 }
681 setFrameReadbackEnabled(false);
682 exit();
683 return;
684 }
685 if (recording_complete) {
686 return;
687 }
688
690 return;
691 }
692
694
695 pollMidi();
697
698 source_frame_received = false;
699 recording_frame_due = false;
701 bool clocked_video_handled = false;
702
706 } else if (initial_frame_pending) {
707 initial_frame_pending = false;
709 } else {
710 double clock_seconds = 0.0;
712 clocked_video_handled = true;
713 if (!readClockedVideoFrame(clock_seconds)) {
714 return;
715 }
716 } else {
717 const bool read_frame = readTrackedInputFrame();
718 if (!read_frame && !handleCaptureEnd()) {
719 return;
720 }
722 }
723 }
724 }
725
727 const bool render_latest_camera_frame = options.maximize_fps && source_kind == SourceKind::Camera && media_timeline_started;
728 if ((source_frame_received || render_latest_camera_frame) && !clocked_video_handled) {
729 recording_frame_due = true;
733 } else {
734 double clock_seconds = 0.0;
735 if (mediaClockSeconds(clock_seconds)) {
736 const double rate = outputFrameRate();
737 const std::uint64_t target_frame = static_cast<std::uint64_t>(std::floor(std::max(clock_seconds, 0.0) * rate));
738 if (target_frame < next_clock_output_frame) {
739 recording_frame_due = false;
740 } else {
742 recording_frame_pts = target_frame;
743 next_clock_output_frame = target_frame + 1;
745 std::cout << "acmxvk: camera recording uses real-time "
746 "PTS; slow frames preserve capture duration\n";
748 }
749 }
750 }
751 }
752 }
753
754 if (!rendering_frozen) {
756 }
758 const VkExtent2D extent = getRenderExtent();
759 const int target_width = extent.width > 0U ? static_cast<int>(extent.width) : options.width;
760 const int target_height = extent.height > 0U ? static_cast<int>(extent.height) : options.height;
761
762 if (!rendering_frozen) {
763 updateShaderUniforms(target_width, target_height);
764 }
766 frame_sprite->drawSpriteRect(0, 0, target_width, target_height);
767 }
770 setFrameReadbackEnabled(snapshot_pending || (continuousReadbackEnabled() && recording_frame_due));
771 }
772#ifdef AUDIO_ENABLED
773
774 // Audio, MIDI, custom controls, and media-clock coordination.
777 audio_warmup_started = false;
778 if (options.audio_warm_rate <= 0.0) {
779 std::cout << "acmxvk: audio shader warmup disabled\n";
780 } else {
781 std::cout << "acmxvk: audio shader warmup " << options.audio_warm_rate << "/second (~" << 1.0 / options.audio_warm_rate << " seconds to full strength)\n";
782 }
783 }
784
785 [[nodiscard]] float MainWindow::updateAudioWarmup(std::chrono::steady_clock::time_point now) {
786 if (options.audio_warm_rate <= 0.0) {
789 }
794 }
795
796 const float delta = std::max(std::chrono::duration<float>(now - audio_warmup_last_tick).count(), 0.0F);
798 audio_warmup_envelope = std::min(audio_warmup_envelope + delta * static_cast<float>(options.audio_warm_rate), 1.0F);
800 }
801#endif
802
804#ifdef ACMXVK_WITH_DNN
805 if (!options.human_model.empty()) {
806 human_segmenter = std::make_unique<dnn::HumanSegmenter>(options.human_model);
807 std::cout << "acmxvk: PP-HumanSeg enabled: " << options.human_model << " (" << (options.human_background ? "background-only shader composition" : "foreground isolation") << ", automatic CPU/CUDA backend selection)\n";
808 }
809 if (!options.edge_model.empty()) {
810 edge_detector = std::make_unique<dnn::EdgeDetector>(options.edge_model);
811 std::cout << "acmxvk: DexiNed edge detection enabled: " << options.edge_model << " (automatic CPU/CUDA backend selection)\n";
812 }
813 if (!options.onnx_configuration.empty()) {
814 generic_onnx_processor = std::make_unique<dnn::GenericOnnxProcessor>(options.onnx_configuration);
815 std::cout << "acmxvk: generic ONNX processing enabled: " << options.onnx_configuration << " (automatic CPU/CUDA backend selection)\n";
816 }
817#endif
818 }
819
821#ifdef ACMXVK_WITH_DEEP_DREAM
822 if (options.dream_model.empty()) {
823 return;
824 }
825 deep_dream_model = std::make_unique<dream::Model>(dream::Model::load(options.dream_model, options.cuda_device, options.dream_layer, options.dream_fp16));
826 const dream::ModelMetadata &metadata = deep_dream_model->metadata();
827 const dream::LayerMetadata &layer = metadata.layers[deep_dream_model->selected_layer()];
828 if (options.dream_channel >= 0 && static_cast<std::size_t>(options.dream_channel) >= deep_dream_model->selected_channels()) {
829 throw std::runtime_error("--dream-channel is outside the selected layer's channel range");
830 }
831 std::cout << "acmxvk: Deep Dream preprocessing enabled: " << metadata.architecture << '/' << layer.name << ", " << options.dream_iterations << " iteration(s), strength " << options.dream_strength << ", feedback " << options.dream_feedback << ", zoom " << options.dream_zoom << ", rotation " << options.dream_rotation << " degrees"
832 << ", working size " << (options.dream_size == 0 ? std::string("native") : std::to_string(options.dream_size) + " max") << ", " << (options.dream_fp16 ? "FP16" : "FP32") << ", channel ";
833 if (options.dream_channel < 0) {
834 std::cout << "all";
835 } else {
836 std::cout << options.dream_channel;
837 }
838 std::cout << ", " << options.dream_octaves << " octave(s) at " << options.dream_octave_scale << "x, jitter " << options.dream_jitter << " px"
839 << ", smoothing " << options.dream_smoothing << " px"
840 << ", acidcam-gpu order " << (options.gpu_filter_before_dream ? "before" : "after") << " Deep Dream"
841 << "; output feeds the existing Vulkan shader chain\n";
843 std::cout << "acmxvk: randomized Deep Dream controls every " << options.random_dream_interval << " media second(s)\n";
844 }
846 std::cout << "acmxvk: traditional " << (options.dream_headless ? "headless" : "preview")
847 << " Deep Dream video mode: "
848 "independent source frames, temporal feedback/zoom/"
849 "rotation disabled, no-drop output\n";
850 }
851#endif
852 }
853
855#ifdef ACMXVK_WITH_STABLE_DIFFUSION
857 return;
858 }
859 fs::path model;
861 model = fs::absolute(options.stable_diffusion_model).lexically_normal();
862 if (!fs::is_regular_file(model)) {
863 throw std::runtime_error("Stable Diffusion model is not a regular file: " + model.string());
864 }
865 }
867 throw std::runtime_error("Stable Diffusion video preview currently supports SDR input only");
868 }
871 settings.model = model;
874 for (const StableDiffusionLora &configured_lora : options.stable_diffusion_loras) {
875 const fs::path lora_model = fs::absolute(configured_lora.file).lexically_normal();
876 if (!fs::is_regular_file(lora_model)) {
877 throw std::runtime_error("Stable Diffusion LoRA model is not a regular file: " + lora_model.string());
878 }
879 if (settings.lora_directory.empty()) {
880 settings.lora_directory = lora_model.parent_path();
881 } else if (settings.lora_directory != lora_model.parent_path()) {
882 throw std::runtime_error("all Stable Diffusion LoRA models must be in the same "
883 "directory");
884 }
885 settings.loras.push_back({lora_model.filename(), configured_lora.multiplier});
886 }
888 const fs::path upscale_model = fs::absolute(options.stable_diffusion_upscale_model).lexically_normal();
889 if (!fs::is_regular_file(upscale_model)) {
890 throw std::runtime_error("Stable Diffusion upscale model is not a regular file: " + upscale_model.string());
891 }
892 settings.upscale_model = upscale_model;
893 }
900 settings.upscale_width = options.width;
901 settings.upscale_height = options.height;
911 const std::shared_ptr<std::atomic_bool> cancelled = stable_diffusion_cancelled;
912 settings.cancelled = [cancelled] { return cancelled->load(std::memory_order_relaxed) || HEADLESS_SHUTDOWN_REQUESTED != 0; };
913 std::cout << "acmxvk: loading " << (settings.upscale_only ? "Stable Diffusion ESRGAN upscaler" : "Stable Diffusion model") << " asynchronously; the preview will begin when it is ready\n";
914 stable_diffusion_initialization = std::async(std::launch::async, [settings = std::move(settings)]() mutable { return std::make_unique<stable_diffusion::Server>(std::move(settings)); });
915 stable_diffusion_initialization_pending = true;
916#endif
917 }
918
920#ifdef ACMXVK_WITH_STABLE_DIFFUSION
921 if (!stable_diffusion_initialization_pending) {
922 return true;
923 }
924 if (stable_diffusion_initialization.wait_for(std::chrono::seconds(0)) != std::future_status::ready) {
925 return false;
926 }
927 stable_diffusion_server = stable_diffusion_initialization.get();
928 stable_diffusion_initialization_pending = false;
929 if (stable_diffusion_initial_frame_deferred) {
930 stable_diffusion_initial_frame_deferred = false;
931 if (!readTrackedInputFrame()) {
932 throw std::runtime_error("capture did not provide an initial frame after Stable "
933 "Diffusion startup");
934 }
936 }
938 std::cout << "acmxvk: Stable Diffusion frame processing enabled after "
939 "the Vulkan shader chain; MXWrite CFR output enabled\n";
940 } else {
941 std::cout << "acmxvk: Stable Diffusion frame processing enabled before "
942 "the Vulkan shader chain"
943 << (options.stable_diffusion_upscale_only ? "; sd-server ESRGAN upscale-only enabled"
944 : options.stable_diffusion_upscale ? "; high-quality compute upscale enabled"
945 : !options.stable_diffusion_upscale_model.empty() ? "; sd-server ESRGAN upscale enabled"
946 : "")
947 << (options.output_file.empty() ? "; windowed preview mode\n" : "; MXWrite CFR output enabled\n");
948 }
949 return true;
950#else
951 return true;
952#endif
953 }
954
956#ifdef ACMXVK_WITH_STABLE_DIFFUSION
957 stable_diffusion_cancelled->store(true, std::memory_order_relaxed);
958 if (!stable_diffusion_initialization.valid()) {
959 return;
960 }
961 try {
962 std::unique_ptr<stable_diffusion::Server> pending_server = stable_diffusion_initialization.get();
963 } catch (const std::exception &error) {
964 std::cerr << "acmxvk: Stable Diffusion startup stopped: " << error.what() << '\n';
965 }
966 stable_diffusion_initialization_pending = false;
967#endif
968 }
969
971#ifdef ACMXVK_WITH_STABLE_DIFFUSION
972 if (stable_diffusion_server == nullptr || options.stable_diffusion_after_shaders || rgba.empty()) {
973 return;
974 }
975 rgba = stable_diffusion_server->process(rgba);
976#else
977 static_cast<void>(rgba);
978#endif
979 }
980
982#ifdef ACMXVK_WITH_CUDA
983 if (options.gpu_filter_indices.empty()) {
984 return;
985 }
986 gpu_filter_engine = std::make_unique<gpu::FilterEngine>(options.gpu_filter_indices, options.gpu_frame_buffer_size);
987#endif
988 }
989
990 void MainWindow::selectGpuFilter(int direction) {
991#ifdef ACMXVK_WITH_CUDA
992 if (gpu_filter_engine != nullptr && gpu_filter_engine->select_relative_filter(direction) && source_kind == SourceKind::Graphic && !graphic_rgba.empty()) {
997 }
998 }
999#else
1000 static_cast<void>(direction);
1001#endif
1002 }
1003
1005#ifdef MIDI_ENABLED
1007 return;
1008 }
1009 midi_input = std::make_unique<midi::MidiInput>();
1010 const int port = options.midi_device_specified ? options.midi_device : 0;
1011 if (!midi_input->open(port)) {
1012 throw std::runtime_error("could not open MIDI input port " + std::to_string(port));
1013 }
1014#endif
1015 }
1016
1018#ifdef MIDI_ENABLED
1019 if (!options.midi_map_file.empty()) {
1022 std::cout << "acmxvk: loaded " << midi_action_mappings.size() << " MIDI mapping(s) from " << options.midi_map_file << '\n';
1023
1024 for (int slider = 0; slider < 4; ++slider) {
1025 const int action = 600 + slider * 2;
1026 const bool mapped = std::any_of(midi_action_mappings.begin(), midi_action_mappings.end(), [&](const midi::MidiMapping &mapping) { return mapping.primary_action == action && mapping.secondary_action == action + 1; });
1027 if (!mapped) {
1028 continue;
1029 }
1030 const std::string name = "slider" + std::to_string(slider + 1);
1031 const auto uniform = std::find_if(custom_uniforms.begin(), custom_uniforms.end(), [&](const ShaderManifest::CustomUniform &candidate) { return candidate.name == name; });
1032 if (uniform == custom_uniforms.end()) {
1033 std::cerr << "acmxvk: MIDI " << name
1034 << " mapping has no matching custom uniform in "
1035 "library.json\n";
1036 continue;
1037 }
1038 midi_slider_uniform_indices[slider] = static_cast<int>(std::distance(custom_uniforms.begin(), uniform));
1039 std::cout << "acmxvk: MIDI Slider " << (slider + 1) << " -> " << name << " [" << uniform->minimum << ", " << uniform->maximum << "]\n";
1040 }
1041
1042 std::size_t active_mappings = 0;
1043 for (const midi::MidiMapping &mapping : midi_action_mappings) {
1044 if (isMidiMappingSupported(mapping)) {
1045 ++active_mappings;
1046 } else if (options.midi_monitor) {
1047 std::cerr << "acmxvk: MIDI map action unavailable in this build: " << mapping.primary_action << ':' << mapping.secondary_action << '\n';
1048 }
1049 }
1050 std::cout << "acmxvk: MIDI map has " << active_mappings << " active mapping(s)";
1051 if (active_mappings != midi_action_mappings.size()) {
1052 std::cout << " and " << (midi_action_mappings.size() - active_mappings) << " mapping(s) reserved for unported ACMX2 controls";
1053 }
1054 std::cout << '\n';
1055 }
1056
1057 for (const std::string &mapping_text : options.midi_cc_mappings) {
1058 const std::size_t equals = mapping_text.find('=');
1059 if (equals == std::string::npos || equals == 0 || equals + 1 >= mapping_text.size() || mapping_text.find('=', equals + 1) != std::string::npos) {
1060 throw std::runtime_error("--midi-cc requires [channel:]CC=uniform: " + mapping_text);
1061 }
1062
1063 const std::string source = trim(mapping_text.substr(0, equals));
1064 const std::string uniform_name = trim(mapping_text.substr(equals + 1));
1065 if (!isValidCustomUniformName(uniform_name)) {
1066 throw std::runtime_error("--midi-cc contains an invalid uniform name: " + uniform_name);
1067 }
1068
1069 int channel = -1;
1070 int controller = 0;
1071 const std::size_t colon = source.find(':');
1072 if (colon == std::string::npos) {
1073 controller = parseInteger(source, "--midi-cc");
1074 } else {
1075 if (colon == 0 || colon + 1 >= source.size() || source.find(':', colon + 1) != std::string::npos) {
1076 throw std::runtime_error("--midi-cc requires [channel:]CC=uniform: " + mapping_text);
1077 }
1078 channel = parseInteger(std::string_view(source).substr(0, colon), "--midi-cc");
1079 controller = parseInteger(std::string_view(source).substr(colon + 1), "--midi-cc");
1080 if (channel < 1 || channel > 16) {
1081 throw std::runtime_error("--midi-cc channel must be between 1 and 16");
1082 }
1083 --channel;
1084 }
1085 if (controller < 0 || controller > 127) {
1086 throw std::runtime_error("--midi-cc controller must be between 0 and 127");
1087 }
1088
1089 const auto uniform = std::find_if(custom_uniforms.begin(), custom_uniforms.end(), [&](const ShaderManifest::CustomUniform &candidate) { return candidate.name == uniform_name; });
1090 if (uniform == custom_uniforms.end()) {
1091 throw std::runtime_error("--midi-cc target is not defined in library.json: " + uniform_name);
1092 }
1093 const std::size_t uniform_index = static_cast<std::size_t>(std::distance(custom_uniforms.begin(), uniform));
1094 const auto duplicate = std::find_if(midi_cc_mappings.begin(), midi_cc_mappings.end(), [&](const MidiCcMapping &mapping) { return mapping.uniform_index == uniform_index; });
1095 if (duplicate != midi_cc_mappings.end()) {
1096 throw std::runtime_error("custom uniform has more than one --midi-cc mapping: " + uniform_name);
1097 }
1098
1099 midi_cc_mappings.push_back({channel, controller, uniform_index, uniform_name});
1100 std::cout << "acmxvk: MIDI " << (channel < 0 ? std::string("any channel") : "channel " + std::to_string(channel + 1)) << " CC " << controller << " -> " << uniform_name << " [" << uniform->minimum << ", " << uniform->maximum << "]\n";
1101 }
1102#endif
1103 }
1104
1105#ifdef MIDI_ENABLED
1106 [[nodiscard]] bool MainWindow::applyMidiCc(const midi::MidiMessage &message) {
1107 if (message.bytes.size() < 3 || (message.bytes[0] & 0xF0U) != 0xB0U) {
1108 return false;
1109 }
1110 const int channel = message.bytes[0] & 0x0FU;
1111 const int controller = message.bytes[1] & 0x7FU;
1112 const int value = message.bytes[2] & 0x7FU;
1113 bool changed = false;
1114 for (const MidiCcMapping &mapping : midi_cc_mappings) {
1115 if (mapping.controller != controller || (mapping.channel >= 0 && mapping.channel != channel)) {
1116 continue;
1117 }
1118 const ShaderManifest::CustomUniform &uniform = custom_uniforms[mapping.uniform_index];
1119 const double normalized = static_cast<double>(value) / 127.0;
1120 const float mapped = static_cast<float>(uniform.minimum + normalized * (uniform.maximum - uniform.minimum));
1121 custom_uniform_values[mapping.uniform_index] = mapped;
1122 changed = true;
1123 if (options.midi_monitor) {
1124 std::cout << "acmxvk: MIDI CC " << controller << " -> " << mapping.uniform_name << '=' << mapped << '\n';
1125 }
1126 }
1127 return changed;
1128 }
1129
1130 [[nodiscard]] SDL_Keycode MainWindow::midiActionKey(int action) const {
1131 switch (action) {
1132 case 262:
1133#ifdef ACMXVK_WITH_CUDA
1134 return gpu_filter_engine != nullptr ? SDLK_RIGHT : SDLK_UNKNOWN;
1135#else
1136 return SDLK_UNKNOWN;
1137#endif
1138 case 263:
1139#ifdef ACMXVK_WITH_CUDA
1140 return gpu_filter_engine != nullptr ? SDLK_LEFT : SDLK_UNKNOWN;
1141#else
1142 return SDLK_UNKNOWN;
1143#endif
1144 case 264:
1145 return SDLK_DOWN;
1146 case 265:
1147 return SDLK_UP;
1148 case 266:
1149 case 504:
1150 return SDLK_PAGEUP;
1151 case 267:
1152 case 505:
1153 return SDLK_PAGEDOWN;
1154 case 268:
1155#ifdef AUDIO_ENABLED
1156 return SDLK_HOME;
1157#else
1158 return SDLK_UNKNOWN;
1159#endif
1160 case 269:
1161#ifdef AUDIO_ENABLED
1162 return SDLK_END;
1163#else
1164 return SDLK_UNKNOWN;
1165#endif
1166 case 260:
1167 return SDLK_INSERT;
1168 case 261:
1169 return SDLK_DELETE;
1170 case 500:
1171 return SDLK_U;
1172 case 501:
1173 return SDLK_I;
1174 case 298:
1175 return SDLK_F9;
1176 case 32:
1177 return SDLK_SPACE;
1178 case 44:
1179 return options.enable_3d ? SDLK_COMMA : SDLK_UNKNOWN;
1180 case 46:
1181 return options.enable_3d ? SDLK_PERIOD : SDLK_UNKNOWN;
1182 case 51:
1183 return options.enable_3d ? SDLK_3 : SDLK_UNKNOWN;
1184 case 52:
1185 return SDLK_4;
1186 case 53:
1187 return SDLK_5;
1188 case 54:
1189 return SDLK_6;
1190 case 67:
1191 return options.enable_3d ? SDLK_C : SDLK_UNKNOWN;
1192 case 79:
1193 return options.enable_3d ? SDLK_O : SDLK_UNKNOWN;
1194 case 91:
1195 return options.enable_3d ? SDLK_MINUS : SDLK_UNKNOWN;
1196 case 93:
1197 return options.enable_3d ? SDLK_EQUALS : SDLK_UNKNOWN;
1198 case 69:
1199 return options.watermark_text.empty() ? SDLK_UNKNOWN : SDLK_E;
1200 case 74:
1201 return SDLK_J;
1202 case 78:
1203 return SDLK_N;
1204 case 75:
1205 return SDLK_K;
1206 case 76:
1207 return SDLK_L;
1208 case 77:
1209 return SDLK_M;
1210 case 80:
1211 return SDLK_P;
1212 case 81:
1213#ifdef AUDIO_ENABLED
1214 return SDLK_Q;
1215#else
1216 return SDLK_UNKNOWN;
1217#endif
1218 case 70:
1219 return SDLK_F;
1220 case 73:
1221 return SDLK_I;
1222 case 84:
1223 return SDLK_T;
1224 case 85:
1225 return SDLK_U;
1226 case 86:
1227 return options.enable_3d ? SDLK_V : SDLK_UNKNOWN;
1228 case 88:
1229 return options.enable_3d ? SDLK_X : SDLK_UNKNOWN;
1230 case 89:
1231 return SDLK_Y;
1232 case 90:
1233 return SDLK_Z;
1234 default:
1235 return SDLK_UNKNOWN;
1236 }
1237 }
1238
1239 [[nodiscard]] bool MainWindow::isMidiSliderMapping(const midi::MidiMapping &mapping) const { return mapping.primary_action >= 600 && mapping.primary_action <= 606 && mapping.primary_action % 2 == 0 && mapping.secondary_action == mapping.primary_action + 1; }
1240
1241 [[nodiscard]] bool MainWindow::usesMidiDeltaDirection(const midi::MidiMapping &mapping) { return mapping.primary_action == 506 || mapping.primary_action == 508 || mapping.primary_action == 512; }
1242
1243 [[nodiscard]] bool MainWindow::isMidiModelAction(int action) const { return options.enable_3d && action >= 506 && action <= 515; }
1244
1245 [[nodiscard]] bool MainWindow::isMidiMappingSupported(const midi::MidiMapping &mapping) const {
1246 if (isMidiSliderMapping(mapping)) {
1247 const int slider = (mapping.primary_action - 600) / 2;
1248 return midi_slider_uniform_indices[slider] >= 0;
1249 }
1250 if (mapping.secondary_action == 0) {
1251 return isMidiModelAction(mapping.primary_action) || midiActionKey(mapping.primary_action) != SDLK_UNKNOWN;
1252 }
1253 const bool primary_supported = isMidiModelAction(mapping.primary_action) || midiActionKey(mapping.primary_action) != SDLK_UNKNOWN;
1254 const bool secondary_supported = isMidiModelAction(mapping.secondary_action) || midiActionKey(mapping.secondary_action) != SDLK_UNKNOWN;
1255 return primary_supported && secondary_supported;
1256 }
1257
1258 [[nodiscard]] std::string_view MainWindow::midiActionName(int action) const {
1259 switch (action) {
1260 case 262:
1261 return "select next CUDA filter";
1262 case 263:
1263 return "select previous CUDA filter";
1264 case 264:
1265 return "next shader or playlist node";
1266 case 265:
1267 return "previous shader or playlist node";
1268 case 266:
1269 case 504:
1270 return "increase shader time speed";
1271 case 267:
1272 case 505:
1273 return "decrease shader time speed";
1274 case 268:
1275 return "toggle audio delta-time scaling";
1276 case 269:
1277 return "toggle spectrum sensitivity scaling";
1278 case 260:
1279 return "increase audio sensitivity";
1280 case 261:
1281 return "decrease audio sensitivity";
1282 case 500:
1283 return "step shader time forward";
1284 case 501:
1285 return "step shader time backward";
1286 case 506:
1287 return "rotate model X forward";
1288 case 507:
1289 return "rotate model X backward";
1290 case 508:
1291 return "rotate model Y forward";
1292 case 509:
1293 return "rotate model Y backward";
1294 case 510:
1295 return "increase 3D manual rotation speed";
1296 case 511:
1297 return "decrease 3D manual rotation speed";
1298 case 512:
1299 return "rotate model Z forward";
1300 case 513:
1301 return "rotate model Z backward";
1302 case 514:
1303 return "increase model scale";
1304 case 515:
1305 return "decrease model scale";
1306 case 298:
1307 return "toggle runtime HUD";
1308 case 32:
1309 return "toggle shader bypass";
1310 case 44:
1311 return "decrease 3D view rotation speed";
1312 case 46:
1313 return "increase 3D view rotation speed";
1314 case 51:
1315 return "toggle 2D/3D rendering";
1316 case 52:
1317 return "take TIFF snapshot";
1318 case 53:
1319 return "take WebP snapshot";
1320 case 54:
1321 return "take raw RGBA snapshot";
1322 case 67:
1323 return "toggle 3D wave effect";
1324 case 79:
1325 return "toggle 3D scale oscillation";
1326 case 91:
1327 return "decrease model scale";
1328 case 93:
1329 return "increase model scale";
1330 case 69:
1331 return "toggle watermark";
1332 case 74:
1333 return "toggle random autopilot";
1334 case 78:
1335 return "toggle random autopilot crossfade";
1336 case 75:
1337 return "toggle shader lock";
1338 case 76:
1339 return "toggle rendering freeze";
1340 case 77:
1341 return "toggle multipass";
1342 case 80:
1343 return "toggle playlist or input pause";
1344 case 81:
1345 return "toggle audio-reactive shader time";
1346 case 70:
1347 return "toggle fullscreen";
1348 case 73:
1349 return "step shader time backward";
1350 case 84:
1351 return "toggle shader time";
1352 case 85:
1353 return "step shader time forward";
1354 case 86:
1355 return "toggle 3D view rotation";
1356 case 88:
1357 return "reset model view";
1358 case 89:
1359 return "toggle sequential autopilot";
1360 case 90:
1361 return "take screenshot";
1362 default:
1363 return "unsupported action";
1364 }
1365 }
1366
1368 if (!model_initialized || !isMidiModelAction(action)) {
1369 return;
1370 }
1371
1372 const auto rotate = [](float &degrees, float amount) {
1373 degrees = std::fmod(degrees + amount, 360.0F);
1374 if (degrees < 0.0F) {
1375 degrees += 360.0F;
1376 }
1377 };
1378 switch (action) {
1379 case 506:
1381 break;
1382 case 507:
1384 break;
1385 case 508:
1387 break;
1388 case 509:
1390 break;
1391 case 510:
1392 model_camera_rotation_speed = std::clamp(model_camera_rotation_speed + 0.5F, 0.5F, 50.0F);
1393 std::cout << "acmxvk: 3D manual rotation speed " << model_camera_rotation_speed << '\n';
1394 break;
1395 case 511:
1396 model_camera_rotation_speed = std::clamp(model_camera_rotation_speed - 0.5F, 0.5F, 50.0F);
1397 std::cout << "acmxvk: 3D manual rotation speed " << model_camera_rotation_speed << '\n';
1398 break;
1399 case 512:
1401 break;
1402 case 513:
1404 break;
1405 case 514:
1406 adjustModelScale(0.05F);
1407 break;
1408 case 515:
1409 adjustModelScale(-0.05F);
1410 break;
1411 default:
1412 break;
1413 }
1414 }
1415
1417 if (isMidiModelAction(action)) {
1418 if (options.midi_monitor) {
1419 std::cout << "acmxvk: MIDI action: " << midiActionName(action) << '\n';
1420 }
1422 return;
1423 }
1424 const SDL_Keycode key = midiActionKey(action);
1425 if (key == SDLK_UNKNOWN) {
1426 return;
1427 }
1428 if (options.midi_monitor) {
1429 std::cout << "acmxvk: MIDI action: " << midiActionName(action) << '\n';
1430 }
1431 SDL_Event midi_event{};
1432 midi_event.type = SDL_EVENT_KEY_DOWN;
1433 midi_event.key.type = SDL_EVENT_KEY_DOWN;
1434 midi_event.key.key = key;
1435 midi_event.key.mod = action == 91 || action == 93 ? SDL_KMOD_SHIFT : SDL_KMOD_NONE;
1436 midi_event.key.repeat = false;
1437 event(midi_event);
1438 }
1439
1440 [[nodiscard]] bool MainWindow::setMidiUniform(std::size_t uniform_index, int value, std::string_view label) {
1441 if (uniform_index >= custom_uniforms.size() || uniform_index >= custom_uniform_values.size()) {
1442 return false;
1443 }
1444 const ShaderManifest::CustomUniform &uniform = custom_uniforms[uniform_index];
1445 const double normalized = static_cast<double>(value) / 127.0;
1446 const float mapped = static_cast<float>(uniform.minimum + normalized * (uniform.maximum - uniform.minimum));
1447 custom_uniform_values[uniform_index] = mapped;
1448 if (options.midi_monitor) {
1449 std::cout << "acmxvk: MIDI " << label << " -> " << uniform.name << '=' << mapped << '\n';
1450 }
1451 return true;
1452 }
1453
1454 [[nodiscard]] bool MainWindow::applyMidiMap(const midi::MidiMessage &message) {
1455 if (message.bytes.size() < 3) {
1456 return false;
1457 }
1458 bool changed = false;
1459 for (std::size_t index = 0; index < midi_action_mappings.size(); ++index) {
1460 const midi::MidiMapping &mapping = midi_action_mappings[index];
1461 if (message.bytes[0] != mapping.status || message.bytes[1] != mapping.data1) {
1462 continue;
1463 }
1464 const int value = message.bytes[2] & 0x7FU;
1465 if (mapping.secondary_action == 0) {
1466 if (message.bytes[2] == mapping.data2) {
1468 }
1469 continue;
1470 }
1471
1472 if (isMidiSliderMapping(mapping)) {
1473 const int slider = (mapping.primary_action - 600) / 2;
1474 const int uniform_index = midi_slider_uniform_indices[slider];
1475 if (uniform_index >= 0) {
1476 changed = setMidiUniform(static_cast<std::size_t>(uniform_index), value, "Slider " + std::to_string(slider + 1)) || changed;
1477 }
1478 continue;
1479 }
1480
1481 MidiKnobState &state = midi_knob_states[index];
1482 if (usesMidiDeltaDirection(mapping) && value != state.previous_value) {
1483 state.direction_action = value > state.previous_value ? mapping.primary_action : mapping.secondary_action;
1484 }
1485 state.previous_value = value;
1486 state.value = value;
1487 state.active = value != 64;
1488 if (!state.active) {
1489 state.frame_counter = 0;
1490 }
1491 }
1492 return changed;
1493 }
1494
1496 for (std::size_t index = 0; index < midi_action_mappings.size(); ++index) {
1497 const midi::MidiMapping &mapping = midi_action_mappings[index];
1498 MidiKnobState &state = midi_knob_states[index];
1499 if (!state.active || mapping.secondary_action == 0 || isMidiSliderMapping(mapping) || !isMidiMappingSupported(mapping)) {
1500 continue;
1501 }
1502
1503 const int distance = std::abs(state.value - 64);
1504 const int frame_skip = std::max(1, 17 - (distance * 16 / 63));
1505 if (++state.frame_counter < frame_skip) {
1506 continue;
1507 }
1508 state.frame_counter = 0;
1509 int action = state.value > 64 ? mapping.primary_action : mapping.secondary_action;
1510 if (usesMidiDeltaDirection(mapping)) {
1511 action = state.direction_action;
1512 if (action == 0) {
1513 continue;
1514 }
1515 }
1516 dispatchMidiAction(action);
1517 }
1518 }
1519#endif
1520
1522 if (frame_sprite != nullptr) {
1523 frame_sprite->setCustomUniforms(custom_uniform_values);
1524 }
1525 for (mxvk::VK_Sprite *sprite : post_process_sprites) {
1526 sprite->setCustomUniforms(custom_uniform_values);
1527 }
1528 }
1529
1531#ifdef MIDI_ENABLED
1532 if (midi_input == nullptr || !midi_input->is_open()) {
1533 return;
1534 }
1535 const std::vector<midi::MidiMessage> messages = midi_input->poll_messages();
1536 bool custom_uniforms_changed = false;
1537 for (const midi::MidiMessage &message : messages) {
1538 custom_uniforms_changed = applyMidiCc(message) || custom_uniforms_changed;
1539 custom_uniforms_changed = applyMidiMap(message) || custom_uniforms_changed;
1540 }
1542 if (custom_uniforms_changed) {
1544 }
1545 if (options.midi_monitor) {
1546 for (const midi::MidiMessage &message : messages) {
1547 std::ostringstream text;
1548 text << "acmxvk: MIDI #" << message.sequence << " +" << std::fixed << std::setprecision(6) << message.delta_seconds << "s [";
1549 for (std::size_t index = 0; index < message.bytes.size(); ++index) {
1550 if (index > 0) {
1551 text << ' ';
1552 }
1553 text << std::hex << std::uppercase << std::setfill('0') << std::setw(2) << static_cast<unsigned int>(message.bytes[index]);
1554 }
1555 text << ']';
1556 std::cout << text.str() << '\n';
1557 }
1558 }
1559 const std::uint64_t dropped = midi_input->dropped_message_count();
1560 if (dropped != observed_midi_drops) {
1561 std::cerr << "acmxvk: MIDI queue dropped " << dropped << " message(s) total\n";
1562 observed_midi_drops = dropped;
1563 }
1564#endif
1565 }
1566
1568 if (!options.enable_audio) {
1569 return;
1570 }
1571#ifdef AUDIO_ENABLED
1572 audio_engine = std::make_unique<audio::AudioEngine>();
1573 audio_engine->set_sensitivity(static_cast<float>(options.audio_sensitivity));
1574 if (!options.audio_file.empty()) {
1575 file_audio_source = std::make_unique<audio::FileAudioSource>();
1576 if (!file_audio_source->open(options.audio_file)) {
1578 std::cerr << "acmxvk: source video has no decodable audio "
1579 "track; continuing with silent audio-reactive "
1580 "values";
1582 std::cerr << " and pass-through disabled";
1583 }
1584 std::cerr << '\n';
1585 file_audio_source.reset();
1586 return;
1587 }
1588 throw std::runtime_error("could not decode --audio-file: " + options.audio_file);
1589 }
1591 std::cout << "acmxvk: source video audio drives shader "
1592 "reactivity\n";
1594 std::cout << "acmxvk: offline source-audio synchronization: "
1595 "analysis follows each decoded video frame\n";
1596 }
1597 }
1600 std::cerr << "acmxvk: file audio output could not be "
1601 "initialized; continuing with silent analysis\n";
1602 }
1604 return;
1605 }
1606 const audio::AudioStreamConfig config{
1607 static_cast<unsigned int>(options.audio_channels),
1608 static_cast<float>(options.audio_sensitivity),
1612 static_cast<float>(options.audio_pass_through_gain),
1613 static_cast<float>(options.audio_recording_gain),
1614 };
1615 if (!audio_engine->open(config)) {
1616 std::cerr << "acmxvk: audio input could not be initialized; "
1617 "continuing with zero-valued audio metrics\n";
1618 audio_engine.reset();
1619 } else {
1621 }
1622#endif
1623 }
1624
1626 if (options.record_audio_file.empty()) {
1627 return;
1628 }
1629#ifdef AUDIO_ENABLED
1630 if (audio_engine == nullptr || file_audio_source != nullptr || !audio_engine->is_open()) {
1631 throw std::runtime_error("--record-audio requires an active live audio input");
1632 }
1633 if (!options.output_file.empty() && !options.png_output) {
1634 return;
1635 }
1636 if (!audio_engine->is_recording() && !audio_engine->start_recording()) {
1637 throw std::runtime_error("could not start standalone microphone recording");
1638 }
1639#endif
1640 }
1641
1643#ifdef AUDIO_ENABLED
1644 if (audioSourceOpen()) {
1645 audio_engine->set_sensitivity(audio_engine->sensitivity() + amount);
1646 options.audio_sensitivity = audio_engine->sensitivity();
1647 std::cout << "acmxvk: audio sensitivity " << options.audio_sensitivity << '\n';
1648 return;
1649 }
1650#else
1651 static_cast<void>(amount);
1652#endif
1653 std::cout << "acmxvk: audio input is not active\n";
1654 }
1655
1656 [[nodiscard]] bool MainWindow::audioSourceOpen() const {
1657#ifdef AUDIO_ENABLED
1658 return audio_engine != nullptr && (audio_engine->is_open() || (file_audio_source != nullptr && file_audio_source->is_open()));
1659#else
1660 return false;
1661#endif
1662 }
1663
1665#ifdef AUDIO_ENABLED
1666 if (audio_engine == nullptr || file_audio_source != nullptr || !audio_engine->is_open() || audio_engine->is_recording() || !writer.is_open() || options.png_output || (options.copy_audio && !options.mute_output && options.record_audio_file.empty())) {
1667 return;
1668 }
1669 if (!audio_engine->start_recording()) {
1670 std::cerr << "acmxvk: could not start live audio recording; "
1671 "continuing with video-only output\n";
1672 }
1673#endif
1674 }
1675
1678 return;
1679 }
1681 hud_session_start = std::chrono::steady_clock::now();
1688#ifdef AUDIO_ENABLED
1690#endif
1692 std::cout << "acmxvk: media timeline started on first source frame\n";
1693 }
1694
1697 return;
1698 }
1699
1700 const auto now = std::chrono::steady_clock::now();
1701 if (paused) {
1703 } else {
1705 }
1707 }
1708
1709 [[nodiscard]] bool MainWindow::mediaClockSeconds(double &seconds) const {
1710#ifdef AUDIO_ENABLED
1711 if (file_audio_source != nullptr && file_audio_source->has_output_clock()) {
1712 seconds = file_audio_source->playback_time();
1713 return true;
1714 }
1715 if ((!options.copy_audio || options.mute_output) && writer.is_open() && audio_engine != nullptr && file_audio_source == nullptr && audio_engine->is_recording()) {
1716 seconds = audio_engine->recording_time();
1717 return true;
1718 }
1719#endif
1721 seconds = hudWallElapsedSeconds();
1722 return true;
1723 }
1725 const auto clock_end = source_playback_clock_paused ? source_playback_pause_start : std::chrono::steady_clock::now();
1726 const auto active_time = clock_end - source_playback_clock_start - source_playback_paused_duration;
1727 seconds = std::max(0.0, std::chrono::duration<double>(active_time).count());
1728 return true;
1729 }
1730 seconds = 0.0;
1731 return false;
1732 }
1733
1735 // Shader discovery, custom uniforms, interface IPC, and playlists.
1737 if (!options.fragment_shader.empty() || !options.compute_shader.empty()) {
1738 const bool compute = !options.compute_shader.empty();
1739 const fs::path shader = fs::absolute(compute ? options.compute_shader : options.fragment_shader).lexically_normal();
1740 const std::string label = compute ? "compute shader" : "fragment shader";
1741 if (shader.extension() != ".spv" || !fs::is_regular_file(shader)) {
1742 throw std::runtime_error(label + " is not a readable .spv file: " + shader.string());
1743 }
1744 input::validate_spirv_file(shader, label);
1745 const mxvk::ShaderModuleInfo module_info = mxvk::inspect_spirv(mxvk::load_spv(shader.string()));
1746 const mxvk::ShaderStage expected_stage = compute ? mxvk::ShaderStage::Compute : mxvk::ShaderStage::Fragment;
1747 if (module_info.stage != expected_stage) {
1748 throw std::runtime_error(label + " SPIR-V entry point has the wrong shader stage: " + shader.string());
1749 }
1750 recordShaderResources(module_info, "shader");
1751 shaders.push_back(shader);
1752 return;
1753 }
1754 if (options.shader_directory.empty()) {
1755 return;
1756 }
1757
1758 shader_library_directory = fs::absolute(options.shader_directory).lexically_normal();
1760 shader_manifest_path = manifest.path;
1763 for (const std::string &entry : manifest.entries) {
1764 const fs::path shader = resolveShaderManifestEntry(shader_library_directory, entry);
1765 if (!shader.empty()) {
1766 input::validate_spirv_file(shader, "shader manifest entry");
1767 const mxvk::ShaderModuleInfo module_info = mxvk::inspect_spirv(mxvk::load_spv(shader.string()));
1768 recordShaderResources(module_info, "shader library");
1769 shaders.push_back(shader);
1770 }
1771 }
1772 std::sort(shaders.begin(), shaders.end(), [](const fs::path &left, const fs::path &right) {
1773 std::string left_text = left.generic_string();
1774 std::string right_text = right.generic_string();
1775 std::transform(left_text.begin(), left_text.end(), left_text.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); });
1776 std::transform(right_text.begin(), right_text.end(), right_text.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); });
1777 return left_text < right_text;
1778 });
1779 if (shaders.empty()) {
1780 throw std::runtime_error("shader manifest contains no readable SPIR-V files: " + shader_manifest_path.string());
1781 }
1782 std::cout << "acmxvk: loaded " << shaders.size() << " shaders from " << shader_manifest_path.string() << '\n';
1783 printCustomUniforms();
1784
1785 if (!options.shader_file.empty()) {
1786 const auto selected = std::find_if(shaders.begin(), shaders.end(), [&](const fs::path &path) {
1787 fs::path requested(options.shader_file);
1788 if (requested.extension() != ".spv") {
1789 requested.replace_extension(".spv");
1790 }
1791 return path.filename() == requested.filename() || path.lexically_relative(shader_library_directory) == requested;
1792 });
1793 if (selected == shaders.end()) {
1794 throw std::runtime_error("shader file is not listed in the manifest: " + options.shader_file);
1795 }
1796 shader_index = static_cast<std::size_t>(std::distance(shaders.begin(), selected));
1797 } else {
1798 const int count = static_cast<int>(shaders.size());
1799 const int wrapped_index = ((options.shader_index % count) + count) % count;
1800 shader_index = static_cast<std::size_t>(wrapped_index);
1801 }
1802 }
1803
1805 for (const std::string &override_text : options.custom_uniform_overrides) {
1806 const std::size_t separator = override_text.find('=');
1807 if (separator == std::string::npos || separator == 0 || separator + 1 >= override_text.size()) {
1808 throw std::runtime_error("--uniform requires name=value: " + override_text);
1809 }
1810 const std::string name = trim(override_text.substr(0, separator));
1811 const double value = parseNumber(trim(override_text.substr(separator + 1)), "--uniform");
1812 const auto match = std::find_if(custom_uniforms.begin(), custom_uniforms.end(), [&](const ShaderManifest::CustomUniform &uniform) { return uniform.name == name; });
1813 if (match == custom_uniforms.end()) {
1814 throw std::runtime_error("custom uniform is not defined in library.json: " + name);
1815 }
1816 match->value = std::clamp(value, match->minimum, match->maximum);
1817 }
1818
1819 custom_uniform_values.clear();
1820 custom_uniform_values.reserve(custom_uniforms.size());
1821 for (const ShaderManifest::CustomUniform &uniform : custom_uniforms) {
1822 custom_uniform_values.push_back(static_cast<float>(uniform.value));
1823 }
1824 }
1825
1827 if (custom_uniforms.empty()) {
1828 return;
1829 }
1830 constexpr std::string_view COMPONENTS = "xyzw";
1831 std::cout << "acmxvk: custom uniforms (binding 1):\n";
1832 for (std::size_t index = 0; index < custom_uniforms.size(); ++index) {
1833 const ShaderManifest::CustomUniform &uniform = custom_uniforms[index];
1834 std::cout << " " << uniform.name << '=' << uniform.value << " -> custom_uniforms[" << (index / 4) << "]." << COMPONENTS[index % 4] << '\n';
1835 }
1836 }
1837
1838 [[nodiscard]] std::string MainWindow::currentShader() const { return shaders.empty() ? std::string{} : shaders[shader_index].string(); }
1839
1840 [[nodiscard]] fs::path MainWindow::resolvedShaderPath(const fs::path &shader) const {
1841 std::error_code error;
1842 const fs::path canonical = fs::weakly_canonical(shader, error);
1843 const std::string key = (error ? shader.lexically_normal() : canonical).string();
1844 const auto override = shader_reload_overrides.find(key);
1845 return override == shader_reload_overrides.end() ? shader : override->second;
1846 }
1847
1848 [[nodiscard]] bool MainWindow::historyCacheEnabled() const { return options.enable_texture_cache || shader_history_required; }
1849
1850 void MainWindow::recordShaderResources(const mxvk::ShaderModuleInfo &module_info, std::string_view source) {
1851 if (module_info.usesHistoryTexture && !shader_history_required) {
1853 std::cout << "acmxvk: enabled shared history for " << source << " binding 2\n";
1854 }
1855 if (module_info.usesSpectrumTexture && !shader_spectrum_required) {
1857 std::cout << "acmxvk: enabled spectrum descriptor for " << source << " binding 3\n";
1858 }
1859 if (module_info.usesSpectrumHistoryTexture && !shader_spectrum_history_required) {
1861 if (options.audio_buffers == 0) {
1862 options.audio_buffers = 8;
1863 }
1864 std::cout << "acmxvk: enabled " << options.audio_buffers << " spectrum-history layers for " << source << " binding 4\n";
1865 }
1866 }
1867
1868 [[nodiscard]] std::uint32_t MainWindow::spectrumBinCount() const {
1869#ifdef AUDIO_ENABLED
1871#else
1873#endif
1874 }
1875
1877#ifdef AUDIO_ENABLED
1878 return true;
1879#else
1881#endif
1882 }
1883
1884 [[nodiscard]] bool MainWindow::spectrumHistoryEnabledForShaders() const { return options.audio_buffers > 0; }
1885
1887 if (!options.interface_shm) {
1888 return;
1889 }
1890
1891 const auto now = std::chrono::steady_clock::now();
1893 return;
1894 }
1895 interface_next_connect_attempt = now + std::chrono::seconds(2);
1896 if (!interface_client.open()) {
1897 return;
1898 }
1899
1900 InterfaceState state;
1901 if (!interface_client.read(state)) {
1903 std::cerr << "acmxvk: could not read compatible interface "
1904 "control state; retrying\n";
1906 }
1907 interface_client.close();
1908 return;
1909 }
1910 const bool reconnected = interface_connection_warning_reported;
1922 std::cout << "acmxvk: interface live shader, multipass, playback, "
1923 "overlay, GPU-filter, Deep Dream, and audio-file control "
1924 "enabled"
1925 << (reconnected ? " (reconnected)" : "") << '\n';
1926 }
1927
1929 if (!options.interface_shm) {
1930 return;
1931 }
1932 if (!interface_client.is_open()) {
1934 return;
1935 }
1936
1937 InterfaceState state;
1938 if (!interface_client.read(state)) {
1940 std::cerr << "acmxvk: interface control connection lost; "
1941 "retrying\n";
1943 }
1944 interface_client.close();
1945 interface_next_connect_attempt = std::chrono::steady_clock::now() + std::chrono::seconds(2);
1946 return;
1947 }
1948 if (state.sequence == interface_last_sequence) {
1949 return;
1950 }
1962 }
1966 }
1967 }
1968
1970 if (options.repeat != requested.repeat) {
1971 options.repeat = requested.repeat;
1972 if (announce) {
1973 std::cout << "acmxvk: interface video repeat " << (options.repeat ? "enabled" : "disabled") << '\n';
1974 }
1975 }
1976 if (options.normalized_time != requested.normalized_time) {
1977 options.normalized_time = requested.normalized_time;
1978 if (announce) {
1979 std::cout << "acmxvk: interface normalized time " << (options.normalized_time ? "enabled" : "disabled") << '\n';
1980 }
1981 }
1982 }
1983
1985 if (options.display_filter != requested.display_filter) {
1986 options.display_filter = requested.display_filter;
1987 if (announce) {
1988 std::cout << "acmxvk: interface display-filter overlay " << (options.display_filter ? "enabled" : "disabled") << '\n';
1989 }
1990 }
1991
1992 try {
1993 input::validate_string(requested.watermark_text, input::StringKind::DisplayText, "interface watermark", true);
1994 } catch (const std::exception &error) {
1995 std::cerr << "acmxvk: rejected interface watermark: " << error.what() << '\n';
1996 return;
1997 }
1998
1999 const bool was_enabled = watermark_enabled && !options.watermark_text.empty();
2000 const bool requested_enabled = requested.watermark_enabled && !requested.watermark_text.empty();
2001 const bool changed = watermark_enabled != requested_enabled || options.watermark_text != requested.watermark_text || options.watermark_color != requested.watermark_color;
2002 if (!changed) {
2003 return;
2004 }
2005
2006 options.watermark_text = requested.watermark_text;
2007 options.watermark_color = requested.watermark_color;
2008 watermark_enabled = requested_enabled;
2009 if (!was_enabled && watermark_enabled) {
2010 counter_disabled = true;
2011 }
2012 if (announce) {
2013 std::cout << "acmxvk: interface watermark " << (watermark_enabled ? "enabled" : "disabled");
2014 if (watermark_enabled) {
2015 std::cout << " (color=" << static_cast<int>(options.watermark_color[0]) << ',' << static_cast<int>(options.watermark_color[1]) << ',' << static_cast<int>(options.watermark_color[2]) << ')';
2016 }
2017 std::cout << '\n';
2018 }
2019 }
2020
2022#ifdef ACMXVK_WITH_CUDA
2023 const bool requested_enabled = requested.enabled && !requested.filter_indices.empty();
2024 const bool currently_enabled = gpu_filter_engine != nullptr;
2025 const std::vector<int> effective_indices = requested_enabled ? requested.filter_indices : std::vector<int>{};
2026 if (requested_enabled == currently_enabled && options.gpu_filter_indices == effective_indices && (!requested_enabled || options.gpu_frame_buffer_size == requested.frame_buffer_size)) {
2027 return;
2028 }
2029
2030 if (requested.enabled && requested.filter_indices.empty()) {
2031 std::cerr << "acmxvk: rejected enabled interface GPU-filter "
2032 "state without any filter indices\n";
2033 return;
2034 }
2035
2036 std::unique_ptr<gpu::FilterEngine> replacement;
2037 if (requested_enabled) {
2038 try {
2039 replacement = std::make_unique<gpu::FilterEngine>(requested.filter_indices, requested.frame_buffer_size);
2040 } catch (const std::exception &error) {
2041 std::cerr << "acmxvk: rejected interface GPU-filter state: " << error.what() << '\n';
2042 return;
2043 }
2044 }
2045
2046 gpu_filter_engine = std::move(replacement);
2047 options.gpu_filter_indices = effective_indices;
2048 if (requested_enabled) {
2049 options.gpu_frame_buffer_size = requested.frame_buffer_size;
2050 }
2051
2052 if (frame_sprite != nullptr && source_kind == SourceKind::Graphic && !graphic_rgba.empty()) {
2054 if (history_initialized) {
2057 }
2058 }
2059
2060 if (announce) {
2061 std::cout << "acmxvk: interface CUDA filter chain " << (requested_enabled ? "enabled" : "disabled");
2062 if (requested_enabled) {
2063 std::cout << " (" << requested.filter_indices.size() << " filters, " << requested.frame_buffer_size << " history frames)";
2064 }
2065 std::cout << '\n';
2066 }
2067#else
2068 if (announce && requested.enabled) {
2069 std::cerr << "acmxvk: ignored interface GPU-filter state: this "
2070 "build does not include acidcam-gpu\n";
2071 }
2072#endif
2073 }
2074
2076#ifdef ACMXVK_WITH_DEEP_DREAM
2077 const bool currently_enabled = deep_dream_model != nullptr;
2078 if (!requested.enabled) {
2079 if (!currently_enabled) {
2080 return;
2081 }
2082 deep_dream_model.reset();
2083#ifdef ACMXVK_WITH_MXVK_CUDA
2084 cuda_dream_rgba.release();
2085#endif
2086 options.dream_model.clear();
2087 options.dream_layer.clear();
2088 options.gpu_filter_before_dream = false;
2090 if (announce) {
2091 std::cout << "acmxvk: interface Deep Dream disabled\n";
2092 }
2093 return;
2094 }
2095
2096 try {
2097 input::validate_string(requested.model_path, input::StringKind::Path, "interface Deep Dream model path");
2098 input::validate_string(requested.layer, input::StringKind::Token, "interface Deep Dream layer");
2099 if (requested.iterations < 1 || requested.iterations > 100) {
2100 throw std::runtime_error("iterations must be between 1 and 100");
2101 }
2102 if (!std::isfinite(requested.strength) || requested.strength <= 0.0F || requested.strength > 10.0F) {
2103 throw std::runtime_error("strength must be greater than 0 and no more than 10");
2104 }
2105 if (!std::isfinite(requested.feedback) || requested.feedback < 0.0F || requested.feedback > 0.99F) {
2106 throw std::runtime_error("feedback must be between 0 and 0.99");
2107 }
2108 if (!std::isfinite(requested.zoom) || requested.zoom < 0.9F || requested.zoom > 1.1F) {
2109 throw std::runtime_error("zoom must be between 0.9 and 1.1");
2110 }
2111 if (!std::isfinite(requested.rotation) || requested.rotation < -5.0F || requested.rotation > 5.0F) {
2112 throw std::runtime_error("rotation must be between -5 and 5 degrees");
2113 }
2114 if (requested.maximum_dimension != 0 && (requested.maximum_dimension < 64 || requested.maximum_dimension > 4096)) {
2115 throw std::runtime_error("maximum dimension must be 0 or between 64 and 4096");
2116 }
2117 if (requested.channel < -1 || requested.channel > 65535) {
2118 throw std::runtime_error("channel must be all channels or between 0 and 65535");
2119 }
2120 if (requested.octaves < 1 || requested.octaves > 8) {
2121 throw std::runtime_error("octaves must be between 1 and 8");
2122 }
2123 if (!std::isfinite(requested.octave_scale) || requested.octave_scale < 1.1F || requested.octave_scale > 3.0F) {
2124 throw std::runtime_error("octave scale must be between 1.1 and 3.0");
2125 }
2126 if (requested.jitter < 0 || requested.jitter > 64) {
2127 throw std::runtime_error("jitter must be between 0 and 64");
2128 }
2129 if (requested.smoothing < 0 || requested.smoothing > 16) {
2130 throw std::runtime_error("smoothing must be between 0 and 16");
2131 }
2132 if (requested.gpu_filter_first) {
2133#ifdef ACMXVK_WITH_CUDA
2134 if (gpu_filter_engine == nullptr) {
2135 throw std::runtime_error("acidcam-gpu-first requires an enabled GPU filter chain");
2136 }
2137#else
2138 throw std::runtime_error("acidcam-gpu-first requires acidcam-gpu support");
2139#endif
2140 if (options.maximize_fps) {
2141 throw std::runtime_error("acidcam-gpu-first cannot be used with maximize FPS");
2142 }
2144 throw std::runtime_error("acidcam-gpu-first supports camera and video input");
2145 }
2146 if (!options.edge_model.empty() || !options.human_model.empty() || !options.onnx_configuration.empty()) {
2147 throw std::runtime_error("acidcam-gpu-first cannot be combined with DNN input effects");
2148 }
2150 throw std::runtime_error("acidcam-gpu-first cannot be enabled for HDR input");
2151 }
2152 }
2153
2154 const bool settings_changed = !currently_enabled || options.dream_model != requested.model_path || options.dream_layer != requested.layer || options.dream_fp16 != requested.fp16 || options.dream_iterations != requested.iterations || options.dream_size != requested.maximum_dimension || options.dream_channel != requested.channel || options.dream_octaves != requested.octaves || options.dream_jitter != requested.jitter || options.dream_smoothing != requested.smoothing || options.dream_strength != requested.strength || options.dream_feedback != requested.feedback || options.dream_zoom != requested.zoom || options.dream_rotation != requested.rotation || options.dream_octave_scale != requested.octave_scale || options.gpu_filter_before_dream != requested.gpu_filter_first;
2155 if (!settings_changed) {
2156 return;
2157 }
2158
2159 const bool reload_model = !currently_enabled || options.dream_model != requested.model_path || options.dream_layer != requested.layer || options.dream_fp16 != requested.fp16;
2160 std::unique_ptr<dream::Model> replacement;
2161 dream::Model *validated_model = deep_dream_model.get();
2162 if (reload_model) {
2163 replacement = std::make_unique<dream::Model>(dream::Model::load(requested.model_path, options.cuda_device, requested.layer, requested.fp16));
2164 validated_model = replacement.get();
2165 }
2166 if (requested.channel >= 0 && static_cast<std::size_t>(requested.channel) >= validated_model->selected_channels()) {
2167 throw std::runtime_error("channel is outside the selected layer's channel range");
2168 }
2169
2170 if (replacement != nullptr) {
2171 deep_dream_model = std::move(replacement);
2172#ifdef ACMXVK_WITH_MXVK_CUDA
2173 cuda_dream_rgba.release();
2174#endif
2175 }
2176 options.dream_model = requested.model_path;
2177 options.dream_layer = requested.layer;
2178 options.dream_fp16 = requested.fp16;
2179 options.dream_iterations = requested.iterations;
2180 options.dream_size = requested.maximum_dimension;
2181 options.dream_channel = requested.channel;
2182 options.dream_octaves = requested.octaves;
2183 options.dream_jitter = requested.jitter;
2184 options.dream_smoothing = requested.smoothing;
2185 options.dream_strength = requested.strength;
2186 options.dream_feedback = requested.feedback;
2187 options.dream_zoom = requested.zoom;
2188 options.dream_rotation = requested.rotation;
2189 options.dream_octave_scale = requested.octave_scale;
2190 options.gpu_filter_before_dream = requested.gpu_filter_first;
2192
2193 if (announce) {
2194 std::cout << "acmxvk: interface Deep Dream settings applied: " << requested.layer << ", " << requested.iterations << " iteration(s), strength " << requested.strength << ", feedback " << requested.feedback << ", zoom " << requested.zoom << ", rotation " << requested.rotation << " degrees, " << (requested.gpu_filter_first ? "acidcam-gpu first" : "Deep Dream first") << (reload_model ? " (model reloaded)" : "") << '\n';
2195 }
2196 } catch (const std::exception &error) {
2197 std::cerr << "acmxvk: rejected interface Deep Dream settings: " << error.what() << '\n';
2198 }
2199#else
2200 if (announce && requested.enabled) {
2201 std::cerr << "acmxvk: ignored interface Deep Dream settings: this "
2202 "build does not include Deep Dream support\n";
2203 }
2204#endif
2205 }
2206
2208#ifdef AUDIO_ENABLED
2209 if (file_audio_source == nullptr || audio_engine == nullptr) {
2210 std::cerr << "acmxvk: ignored live audio-file change because this "
2211 "process was not started in audio-file mode\n";
2212 return;
2213 }
2214 if (requested.path.empty()) {
2215 std::cerr << "acmxvk: rejected empty interface audio-file request\n";
2216 return;
2217 }
2218
2219 auto replacement = std::make_unique<audio::FileAudioSource>();
2220 try {
2221 if (!replacement->open(requested.path)) {
2222 std::cerr << "acmxvk: could not switch file audio to: " << requested.path << '\n';
2223 return;
2224 }
2225 } catch (const std::exception &error) {
2226 std::cerr << "acmxvk: rejected interface audio-file request: " << error.what() << '\n';
2227 return;
2228 }
2229
2230 replacement->set_repeat(requested.repeat);
2231 if (requested.pass_through && !replacement->enable_output(requested.output_device, static_cast<float>(options.audio_pass_through_gain))) {
2232 std::cerr << "acmxvk: live audio-file output could not be opened; "
2233 "continuing with visual reactivity only\n";
2234 }
2235
2236 file_audio_source->stop_output();
2237 file_audio_source = std::move(replacement);
2238 options.audio_file = requested.path;
2239 options.audio_output_device = requested.output_device;
2240 options.audio_pass_through = requested.pass_through;
2241 options.audio_trunc = requested.trunc;
2242 options.audio_repeat = requested.repeat;
2243 audio_engine->reset();
2245 std::cout << "acmxvk: switched file audio to: " << file_audio_source->path() << " (repeat=" << (options.audio_repeat ? "on" : "off") << ", trunc=" << (options.audio_trunc ? "on" : "off") << ", pass-through=" << (options.audio_pass_through ? "on" : "off") << ")\n";
2246#else
2247 static_cast<void>(requested);
2248 std::cerr << "acmxvk: ignored interface audio-file request: this "
2249 "build does not include audio support\n";
2250#endif
2251 }
2252
2254 if (requested.path.empty()) {
2255 std::cerr << "acmxvk: rejected empty interface shader reload\n";
2256 return;
2257 }
2258
2259 try {
2260 input::validate_string(requested.path, input::StringKind::Path, "interface shader reload path");
2261 } catch (const std::exception &error) {
2262 std::cerr << "acmxvk: rejected interface shader reload: " << error.what() << '\n';
2263 return;
2264 }
2265
2266 std::error_code error;
2267 const fs::path requested_path = fs::weakly_canonical(requested.path, error);
2268 if (error || requested_path.empty() || !fs::is_regular_file(requested_path)) {
2269 std::cerr << "acmxvk: interface shader reload file is not "
2270 "readable: "
2271 << requested.path << '\n';
2272 return;
2273 }
2274
2275 std::size_t logical_index = shaders.size();
2276 const auto shader_match = std::find_if(shaders.begin(), shaders.end(), [&](const fs::path &shader) {
2277 std::error_code shader_error;
2278 const fs::path canonical_shader = fs::weakly_canonical(shader, shader_error);
2279 return !shader_error && canonical_shader == requested_path;
2280 });
2281 if (shader_match != shaders.end()) {
2282 logical_index = static_cast<std::size_t>(std::distance(shaders.begin(), shader_match));
2283 } else if (requested.shader_index >= 0 && static_cast<std::size_t>(requested.shader_index) < shaders.size()) {
2284 logical_index = static_cast<std::size_t>(requested.shader_index);
2285 }
2286 if (logical_index >= shaders.size()) {
2287 std::cerr << "acmxvk: interface shader reload does not identify "
2288 "a shader in the active runtime library: "
2289 << requested_path.string() << '\n';
2290 return;
2291 }
2292
2293 const fs::path logical_shader = shaders[logical_index];
2294 std::error_code logical_error;
2295 const fs::path canonical_logical = fs::weakly_canonical(logical_shader, logical_error);
2296 if (logical_error || canonical_logical.empty()) {
2297 std::cerr << "acmxvk: interface shader reload could not resolve "
2298 "its runtime-library shader\n";
2299 return;
2300 }
2301 const std::string logical_key = canonical_logical.string();
2302 const fs::path previously_resolved = resolvedShaderPath(logical_shader);
2303
2304 mxvk::ShaderModuleInfo module_info;
2305 try {
2306 input::validate_spirv_file(requested_path, "interface shader reload");
2307 module_info = mxvk::inspect_spirv(mxvk::load_spv(requested_path.string()));
2308 } catch (const std::exception &reload_error) {
2309 std::cerr << "acmxvk: rejected compiled shader reload: " << reload_error.what() << '\n';
2310 return;
2311 }
2312
2313 const bool history_before = shader_history_required;
2314 const bool spectrum_before = shader_spectrum_required;
2315 const bool spectrum_history_before = shader_spectrum_history_required;
2316 recordShaderResources(module_info, "live shader reload");
2317 const bool resources_grew = history_before != shader_history_required || spectrum_before != shader_spectrum_required || spectrum_history_before != shader_spectrum_history_required;
2318
2319 const std::vector<fs::path> active_pipeline = activeShaderPipeline();
2320 std::error_code active_error;
2321 const fs::path canonical_previous = fs::weakly_canonical(previously_resolved, active_error);
2322 const bool active = !active_error && std::any_of(active_pipeline.begin(), active_pipeline.end(), [&](const fs::path &shader) {
2323 std::error_code shader_error;
2324 return fs::weakly_canonical(shader, shader_error) == canonical_previous && !shader_error;
2325 });
2326 if (requested_path == canonical_logical)
2327 shader_reload_overrides.erase(logical_key);
2328 else
2329 shader_reload_overrides[logical_key] = requested_path;
2330 if (active && frame_sprite != nullptr) {
2331 model_effect_shader.clear();
2332 if (resources_grew) {
2334 } else {
2337 }
2338 std::cout << "acmxvk: live reloaded active " << (module_info.stage == mxvk::ShaderStage::Compute ? "compute" : "fragment") << " shader: " << requested_path.string() << '\n';
2339 } else {
2340 std::cout << "acmxvk: live compiled shader ready for its next "
2341 "use: "
2342 << requested_path.string() << '\n';
2343 }
2344 }
2345
2347 std::vector<fs::path> requested_passes;
2348 if (requested.enabled) {
2349 if (requested.shader_names.empty()) {
2350 std::cerr << "acmxvk: rejected enabled interface multipass "
2351 "state without any shader passes\n";
2352 return;
2353 }
2354 requested_passes.reserve(requested.shader_names.size());
2355 for (const std::string &name : requested.shader_names) {
2356 const fs::path requested_path(name);
2357 const bool has_parent_reference = std::any_of(requested_path.begin(), requested_path.end(), [](const fs::path &part) { return part == ".."; });
2358 if (requested_path.is_absolute() || has_parent_reference) {
2359 std::cerr << "acmxvk: rejected unsafe interface "
2360 "multipass shader name: "
2361 << name << '\n';
2362 return;
2363 }
2364 const fs::path shader = find_shader_path(shaders, shader_library_directory, name);
2365 if (shader.empty()) {
2366 std::cerr << "acmxvk: interface multipass shader is not "
2367 "in the active library: "
2368 << name << '\n';
2369 return;
2370 }
2371 requested_passes.push_back(shader);
2372 }
2373 }
2374
2375 const bool requested_enabled = requested.enabled && !requested_passes.empty();
2376 if (multipass_enabled == requested_enabled && configured_passes == requested_passes) {
2377 return;
2378 }
2379 if (frame_sprite != nullptr && shader_locked) {
2380 std::cerr << "acmxvk: interface multipass update ignored while "
2381 "shader switching is locked\n";
2382 return;
2383 }
2384
2385 if (frame_sprite != nullptr) {
2387 }
2388 configured_passes = std::move(requested_passes);
2389 multipass_enabled = requested_enabled;
2390 if (frame_sprite != nullptr) {
2394 }
2395
2396 if (multipass_enabled) {
2397 std::cout << "acmxvk: interface multipass enabled (" << configured_passes.size() << " passes)";
2398 for (const fs::path &shader : configured_passes) {
2399 std::cout << "\n " << shader.filename().string();
2400 }
2401 std::cout << '\n';
2402 } else {
2403 std::cout << "acmxvk: interface multipass disabled\n";
2404 }
2405 }
2406
2407 void MainWindow::apply_interface_shader_selection(const std::string &requested_name) {
2408 if (requested_name.empty()) {
2409 return;
2410 }
2411
2412 const fs::path requested(requested_name);
2413 const bool has_parent_reference = std::any_of(requested.begin(), requested.end(), [](const fs::path &part) { return part == ".."; });
2414 if (requested.is_absolute() || has_parent_reference) {
2415 std::cerr << "acmxvk: rejected unsafe interface shader name: " << requested_name << '\n';
2416 return;
2417 }
2418
2419 const fs::path shader = find_shader_path(shaders, shader_library_directory, requested_name);
2420 const auto match = std::find(shaders.begin(), shaders.end(), shader);
2421 if (shader.empty() || match == shaders.end()) {
2422 std::cerr << "acmxvk: interface shader is not in the active "
2423 "library: "
2424 << requested_name << '\n';
2425 return;
2426 }
2427
2428 const std::size_t next_index = static_cast<std::size_t>(std::distance(shaders.begin(), match));
2429 if (next_index == shader_index) {
2430 return;
2431 }
2432 if (shader_locked || frame_sprite == nullptr) {
2433 std::cerr << "acmxvk: interface shader selection ignored while "
2434 "shader switching is locked\n";
2435 return;
2436 }
2437
2439 shader_index = next_index;
2443 std::cout << "acmxvk: interface selected " << activeShaderRole() << ' ' << (shader_index + 1) << '/' << shaders.size() << ": " << currentShader() << '\n';
2444 }
2445
2446 void MainWindow::apply_interface_uniform_values(const std::vector<InterfaceUniformValue> &uniform_values) {
2447 if (uniform_values.empty()) {
2448 return;
2449 }
2450
2451 std::size_t changed_count = 0;
2452 std::size_t ignored_count = 0;
2453 for (const InterfaceUniformValue &incoming : uniform_values) {
2454 if (!isValidCustomUniformName(incoming.name) || !std::isfinite(incoming.value)) {
2455 ++ignored_count;
2456 continue;
2457 }
2458 const auto match = std::find_if(custom_uniforms.begin(), custom_uniforms.end(), [&](const ShaderManifest::CustomUniform &uniform) { return uniform.name == incoming.name; });
2459 if (match == custom_uniforms.end()) {
2460 ++ignored_count;
2461 continue;
2462 }
2463 const std::size_t index = static_cast<std::size_t>(std::distance(custom_uniforms.begin(), match));
2464 if (index >= custom_uniform_values.size()) {
2465 ++ignored_count;
2466 continue;
2467 }
2468 const float value = static_cast<float>(std::clamp(static_cast<double>(incoming.value), match->minimum, match->maximum));
2469 if (custom_uniform_values[index] == value) {
2470 continue;
2471 }
2472 custom_uniform_values[index] = value;
2473 ++changed_count;
2474 }
2475
2476 if (changed_count > 0) {
2478 std::cout << "acmxvk: interface updated " << changed_count << " custom uniform(s)\n";
2479 }
2480 if (ignored_count > 0) {
2481 std::cerr << "acmxvk: interface ignored " << ignored_count << " unknown or invalid custom uniform(s)\n";
2482 }
2483 }
2484
2486 for (const int index : options.shader_pass_indices) {
2487 if (index < 0 || index >= static_cast<int>(shaders.size())) {
2488 throw std::runtime_error("shader pass index is out of range: " + std::to_string(index));
2489 }
2490 configured_passes.push_back(shaders[static_cast<std::size_t>(index)]);
2491 }
2492 for (const std::string &name : options.shader_pass_files) {
2493 const fs::path shader = find_shader_path(shaders, shader_library_directory, name);
2494 if (shader.empty()) {
2495 throw std::runtime_error("shader pass file is not listed in the manifest: " + name);
2496 }
2497 configured_passes.push_back(shader);
2498 }
2500 }
2501
2503 if (options.playlist_file.empty()) {
2504 return;
2505 }
2506 playlist = load_playlist(options.playlist_file, shaders, shader_library_directory, std::cerr);
2507 playlist_enabled = options.enable_playlist;
2508 std::cout << "acmxvk: playlist loaded " << playlist_shader_count(playlist) << " shaders in " << playlist.size() << " nodes from " << options.playlist_file << '\n';
2509 if (options.enable_random_autopilot && !playlist.empty()) {
2510 std::uniform_int_distribution<std::size_t> distribution(0, playlist.size() - 1);
2511 playlist_index = distribution(autopilot_rng);
2512 logSelectedPlaylistNode("randomly selected initial");
2513 } else {
2514 logSelectedPlaylistNode("selected");
2515 }
2516 }
2517 // Resource resolution, HUD/watermark drawing, and DNN overlays.
2519 const auto resolve = [&](std::string &path, const fs::path &resource_subdirectory, std::string_view label) {
2520 if (path.empty() || fs::is_regular_file(path) || fs::path(path).is_absolute()) {
2521 return;
2522 }
2523 fs::path resolved = find_resource(options, fs::path(path));
2524 if (resolved.empty()) {
2525 resolved = find_resource(options, resource_subdirectory / fs::path(path));
2526 }
2527 if (!resolved.empty()) {
2528 path = resolved.string();
2529 std::cout << "acmxvk: " << label << " (resource path): " << path << '\n';
2530 }
2531 };
2532 resolve(options.playlist_file, "playlists", "playlist");
2533 resolve(options.midi_map_file, "midi-examples", "MIDI map");
2534 if (options.enable_3d) {
2535 if (options.model_file.empty()) {
2536 options.model_file = default_model_path(options).string();
2537 std::cout << "acmxvk: 3D model (default): " << options.model_file << '\n';
2538 } else {
2539 resolve(options.model_file, "models", "3D model");
2540 }
2541
2542 std::string model_name = fs::path(options.model_file).filename().string();
2543 std::transform(model_name.begin(), model_name.end(), model_name.begin(), [](unsigned char character) { return static_cast<char>(std::tolower(character)); });
2544 if (!model_name.ends_with(".obj") && !model_name.ends_with(".mxmod") && !model_name.ends_with(".mxmod.z")) {
2545 throw std::runtime_error("--model requires an .obj, .mxmod, or .mxmod.z file");
2546 }
2547 if (!fs::is_regular_file(options.model_file)) {
2548 throw std::runtime_error("3D model was not found: " + options.model_file);
2549 }
2550 constexpr std::uintmax_t MAX_MODEL_BYTES = 1024U * 1024U * 1024U;
2551 input::validate_file_size(options.model_file, "3D model", MAX_MODEL_BYTES);
2552 }
2553 }
2554
2556 if (counter_disabled && !options.display_filter && options.watermark_text.empty() && !options.interface_shm) {
2557 return;
2558 }
2559
2560 const fs::path font = overlay_font_path(options);
2561 if (!fs::is_regular_file(font)) {
2562 throw std::runtime_error("overlay font was not found: " + font.string());
2563 }
2564 const VkExtent2D preview_extent = getSwapchainExtent();
2565 const int preview_height = preview_extent.height > 0U ? static_cast<int>(preview_extent.height) : options.height;
2566 constexpr int FONT_HEIGHT_DIVISOR = 60;
2567 overlay_font_size = std::max(12, preview_height / FONT_HEIGHT_DIVISOR);
2569 setFont(font.string(), overlay_font_size);
2570 setPreviewFont(font.string(), preview_overlay_font_size);
2571 std::cout << "acmxvk: window-scaled output/HUD font " << font.string() << " at " << overlay_font_size << " points\n";
2572 }
2573
2574 [[nodiscard]] std::string MainWindow::clipOverlayText(std::string text) {
2575 constexpr std::size_t MAX_OVERLAY_CHARACTERS = 120;
2576 return input::truncate_utf8(text, MAX_OVERLAY_CHARACTERS);
2577 }
2578
2579 [[nodiscard]] const std::vector<fs::path> *MainWindow::activePasses() const {
2580 if (playlist_enabled && !playlist.empty()) {
2581 return &playlist[playlist_index].shaders;
2582 }
2583 if (multipass_enabled && !configured_passes.empty()) {
2584 return &configured_passes;
2585 }
2586 return nullptr;
2587 }
2588
2589 [[nodiscard]] std::string_view MainWindow::activeShaderRole() const {
2590 const std::vector<fs::path> *passes = activePasses();
2591 return passes != nullptr && !passes->empty() ? "Post-shader" : "Shader";
2592 }
2593
2594 [[nodiscard]] std::string MainWindow::activePassDescription() const {
2595 const std::vector<fs::path> *passes = activePasses();
2596 if (passes == nullptr || passes->empty()) {
2597 return {};
2598 }
2599
2600 std::string description = "Multipass: ";
2601 for (std::size_t index = 0; index < passes->size(); ++index) {
2602 if (index > 0U) {
2603 description += ", ";
2604 }
2605 description += (*passes)[index].filename().string();
2606 }
2607 return clipOverlayText(std::move(description));
2608 }
2609
2610 [[nodiscard]] std::string MainWindow::activePlaylistDescription() const {
2611 if (!playlist_enabled || playlist.empty()) {
2612 return {};
2613 }
2614 std::ostringstream description;
2615 description << "Playlist [" << (playlist_index + 1) << '/' << playlist.size() << "]: " << playlist[playlist_index].name;
2616 return clipOverlayText(description.str());
2617 }
2618
2619 [[nodiscard]] std::string MainWindow::formatHudTime(double seconds_value) {
2620 const double finite_seconds = std::isfinite(seconds_value) ? seconds_value : 0.0;
2621 const auto elapsed = static_cast<std::uint64_t>(std::floor(std::max(0.0, finite_seconds)));
2622 const std::uint64_t hours = elapsed / 3600U;
2623 const std::uint64_t minutes = (elapsed / 60U) % 60U;
2624 const std::uint64_t seconds = elapsed % 60U;
2625 std::ostringstream text;
2626 text << std::setfill('0') << std::setw(2) << hours << ':' << std::setw(2) << minutes << ':' << std::setw(2) << seconds;
2627 return text.str();
2628 }
2629
2631 SDL_Window *window = getSDLWindow();
2632 if (window == nullptr) {
2633 return;
2634 }
2635
2636 const auto now = std::chrono::steady_clock::now();
2637 constexpr auto UPDATE_INTERVAL = std::chrono::milliseconds(500);
2638 if (!force && window_title_last_update.time_since_epoch().count() != 0 && now - window_title_last_update < UPDATE_INTERVAL) {
2639 return;
2640 }
2642
2643 const bool recording = writer.is_open() || options.png_output;
2644 double elapsed_seconds = hudWallElapsedSeconds();
2645 std::uint64_t displayed_frames = frame_count;
2646 if (recording && recording_fps > 0.0) {
2647 displayed_frames = output_frame_count;
2648 elapsed_seconds = writer.is_open() ? writer.get_duration() : static_cast<double>(output_frame_count) / recording_fps;
2649 } else if (source_kind == SourceKind::Video) {
2650 displayed_frames = video_source_frame_count;
2651 elapsed_seconds = hudVideoPositionSeconds();
2652 }
2653
2654 std::ostringstream title;
2656 title << "ACMXVK - Graphics Mode - " << formatHudTime(elapsed_seconds) << " [" << displayed_frames << " frames]";
2657 } else if (source_kind == SourceKind::Video) {
2658 const std::uint64_t total_frames = video_duration_seconds > 0.0 && video_source_fps > 0.0 ? static_cast<std::uint64_t>(std::llround(video_duration_seconds * video_source_fps)) : 0U;
2659 title << "ACMXVK - [" << video_source_frame_count << '/';
2660 if (total_frames > 0U) {
2661 title << total_frames;
2662 } else {
2663 title << '?';
2664 }
2665 title << "] - " << formatHudTime(elapsed_seconds) << " - Video Mode";
2666 } else {
2667 title << "ACMXVK - Capture Mode - " << formatHudTime(elapsed_seconds) << " [" << displayed_frames << " frames]";
2668 }
2669
2670 if (recording) {
2671 title << " (Recording)";
2672 if (writer.is_open()) {
2673 constexpr double BYTES_PER_MEGABYTE = 1024.0 * 1024.0;
2674 const double file_size_mb = static_cast<double>(writer.get_bytes_written()) / BYTES_PER_MEGABYTE;
2675 title << " [File: " << std::fixed << std::setprecision(2) << file_size_mb << " MB]";
2676 const std::string bitrate = format_bitrate(writer.get_bytes_written(), elapsed_seconds);
2677 if (!bitrate.empty()) {
2678 title << " [Bitrate: " << bitrate << ']';
2679 }
2680 }
2681 } else {
2682 title << " (Preview)";
2683 }
2684
2685 const std::string text = title.str();
2686 SDL_SetWindowTitle(window, text.c_str());
2687 }
2688
2690 if (!options.headless || recording_fps <= 0.0 || output_frame_count == 0U) {
2691 return;
2692 }
2693
2694 std::uint64_t expected_frames = 0U;
2695 if (options.repeat) {
2696 const auto duration_frames = static_cast<std::uint64_t>(std::ceil(options.duration * recording_fps));
2697 expected_frames = std::max<std::uint64_t>(1U, duration_frames);
2698 } else if (options.duration > 0.0) {
2699 const auto duration_frames = static_cast<std::uint64_t>(std::ceil(options.duration * recording_fps));
2700 expected_frames = std::max<std::uint64_t>(1U, duration_frames);
2701 }
2702 if (!options.repeat && source_kind == SourceKind::Video && video_duration_seconds > 0.0) {
2703 const auto source_frames = static_cast<std::uint64_t>(std::ceil(video_duration_seconds * recording_fps));
2704 if (expected_frames == 0U) {
2705 expected_frames = source_frames;
2706 } else {
2707 expected_frames = std::min(expected_frames, source_frames);
2708 }
2709 }
2710 if (complete && expected_frames == 0U) {
2711 expected_frames = output_frame_count;
2712 }
2713
2714 const auto now = std::chrono::steady_clock::now();
2715 int percent = -1;
2716 if (expected_frames > 0U) {
2717 const std::uint64_t processed_frames = complete ? expected_frames : std::min(output_frame_count, expected_frames);
2718 percent = static_cast<int>((static_cast<double>(processed_frames) / static_cast<double>(expected_frames)) * 100.0);
2719 if (!complete) {
2720 percent = std::min(percent, 99);
2721 }
2722 }
2723
2724 const bool percent_changed = percent >= 0 && percent > headless_progress_last_percent;
2725 const bool time_elapsed = headless_progress_last_emit.time_since_epoch().count() == 0 || now - headless_progress_last_emit >= std::chrono::milliseconds(500);
2726 if (!complete && !percent_changed && !time_elapsed) {
2727 return;
2728 }
2729
2732 const std::uint64_t processed_frames = complete && expected_frames > 0U ? expected_frames : output_frame_count;
2733 const std::uint64_t written_frames = writer.is_open() ? static_cast<std::uint64_t>(std::max<std::int64_t>(0, writer.get_frame_count())) : png_frame_count;
2734 const double elapsed_seconds = static_cast<double>(processed_frames) / recording_fps;
2735 const double wall_elapsed_seconds = hudWallElapsedSeconds();
2736 const bool estimate_available = expected_frames > 0U && processed_frames > 0U;
2737 double estimated_remaining_seconds = 0.0;
2738 if (estimate_available && !complete) {
2739 const double average_seconds_per_frame = wall_elapsed_seconds / static_cast<double>(processed_frames);
2740 estimated_remaining_seconds = average_seconds_per_frame * static_cast<double>(expected_frames - processed_frames);
2741 }
2742
2743 std::cout << "acmxvk: [";
2744 if (percent >= 0) {
2745 std::cout << std::setw(3) << percent << '%';
2746 } else {
2747 std::cout << " ?%";
2748 }
2749 std::cout << "] Frame " << processed_frames << '/';
2750 if (expected_frames > 0U) {
2751 std::cout << expected_frames;
2752 } else {
2753 std::cout << '?';
2754 }
2755 std::cout << " | Written: " << written_frames << " | Time: " << formatHudTime(elapsed_seconds) << " | Elapsed: " << formatHudTime(wall_elapsed_seconds) << " | Estimated: ";
2756 if (estimate_available) {
2757 std::cout << formatHudTime(estimated_remaining_seconds);
2758 } else {
2759 std::cout << "--:--:--";
2760 }
2761 if (writer.is_open()) {
2762 constexpr double BYTES_PER_MEGABYTE = 1024.0 * 1024.0;
2763 const std::uint64_t bytes_written = writer.get_bytes_written();
2764 const double file_size_mb = static_cast<double>(bytes_written) / BYTES_PER_MEGABYTE;
2765 std::ostringstream size_text;
2766 size_text << std::fixed << std::setprecision(2) << file_size_mb;
2767 std::cout << " | Size: " << size_text.str() << " MB";
2768 const std::string bitrate = format_bitrate(bytes_written, elapsed_seconds);
2769 if (!bitrate.empty()) {
2770 std::cout << " | Bitrate: " << bitrate;
2771 }
2772 }
2773 std::cout << '\n' << std::flush;
2774 }
2775
2776 [[nodiscard]] double MainWindow::hudWallElapsedSeconds() const { return std::max(0.0, std::chrono::duration<double>(std::chrono::steady_clock::now() - hud_session_start).count()); }
2777
2778 [[nodiscard]] bool MainWindow::currentVideoTimeline(double &timeline, std::uint64_t *frame_index) const {
2779 if (source_kind != SourceKind::Video || video_source_frame_count == 0U || !std::isfinite(video_source_fps) || video_source_fps <= 0.0) {
2780 return false;
2781 }
2782 const std::uint64_t index = video_source_frame_count - 1U;
2783 timeline = static_cast<double>(index) / video_source_fps;
2784 if (frame_index != nullptr) {
2785 *frame_index = index;
2786 }
2787 return true;
2788 }
2789
2790 [[nodiscard]] double MainWindow::hudVideoPositionSeconds() const {
2791 double position = 0.0;
2792 if (!currentVideoTimeline(position)) {
2793 return 0.0;
2794 }
2795 if (video_duration_seconds > 0.0) {
2796 position = std::min(position, video_duration_seconds);
2797 }
2798 return std::max(0.0, position);
2799 }
2800
2801 [[nodiscard]] std::string MainWindow::hudVideoTimeString() const {
2802 std::string text = "Video: " + formatHudTime(hudVideoPositionSeconds()) + " / ";
2803 text += video_duration_seconds > 0.0 ? formatHudTime(video_duration_seconds) : "--:--:--";
2804 return text;
2805 }
2806
2807 [[nodiscard]] std::string MainWindow::hudElapsedTimeString() const { return "Elapsed: " + formatHudTime(hudWallElapsedSeconds()); }
2808
2811 const auto now = std::chrono::steady_clock::now();
2812 const double elapsed = std::chrono::duration<double>(now - hud_fps_last_tick).count();
2813 if (elapsed < 0.5) {
2814 return;
2815 }
2816 hud_display_fps = static_cast<double>(hud_fps_frame_count) / elapsed;
2818 hud_fps_last_tick = now;
2819 }
2820
2822 if (!options.maximize_fps || options.requested_fps <= 0.0) {
2823 return;
2824 }
2825
2826 const auto interval = std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(1.0 / options.requested_fps));
2827 const auto now = std::chrono::steady_clock::now();
2828 if (!render_pacing_started) {
2829 render_pacing_started = true;
2830 next_render_tick = now;
2831 return;
2832 }
2833
2834 next_render_tick += interval;
2835 if (next_render_tick > now) {
2836 std::this_thread::sleep_until(next_render_tick);
2837 return;
2838 }
2839
2840 if (now - next_render_tick > interval * 4) {
2841 next_render_tick = now;
2842 }
2843 }
2844
2847 return;
2848 }
2849
2850 const auto now = std::chrono::steady_clock::now();
2851 if (camera_fps_frame_count == 0) {
2854 return;
2855 }
2856
2858 const double elapsed = std::chrono::duration<double>(now - camera_fps_last_tick).count();
2859 if (elapsed < 1.0) {
2860 return;
2861 }
2862
2863 camera_delivered_fps = static_cast<double>(camera_fps_frame_count - 1) / elapsed;
2866
2867 const double log_threshold = std::max(5.0, camera_last_logged_fps * 0.2);
2868 if (camera_last_logged_fps <= 0.0 || std::abs(camera_delivered_fps - camera_last_logged_fps) >= log_threshold) {
2869 std::ostringstream status;
2870 status << "acmxvk: camera delivery: " << std::fixed << std::setprecision(1) << camera_delivered_fps << " FPS measured";
2871 if (camera_reported_fps > 0.0) {
2872 status << " (driver reports " << camera_reported_fps << " FPS)";
2873 }
2874 std::cout << status.str() << '\n';
2876 }
2877 }
2878
2879 void MainWindow::queueRuntimeHud(int &y, int line_height) {
2880 if (counter_disabled) {
2881 return;
2882 }
2884
2885 const SDL_Color shader_color{0U, 96U, 255U, 255U};
2886 std::string shader = effects_enabled ? fs::path(currentShader()).filename().string() : "bypassed";
2887 if (shader_locked) {
2888 shader += " [locked]";
2889 }
2890 printPreviewText(clipOverlayText(std::string(activeShaderRole()) + ": " + std::move(shader)), 10, y, shader_color);
2891 y += line_height;
2892
2893 const SDL_Color crossfade_color{255U, 192U, 0U, 255U};
2894 std::ostringstream crossfade_status;
2895 crossfade_status << "XFade [" << (crossfade_shader_index + 1) << '/' << CROSSFADE_NAMES.size() << "]: " << CROSSFADE_NAMES[crossfade_shader_index];
2896 printPreviewText(clipOverlayText(crossfade_status.str()), 10, y, crossfade_color);
2897 y += line_height;
2898
2899 const std::string playlist_description = activePlaylistDescription();
2900 if (!playlist_description.empty()) {
2901 const SDL_Color playlist_color{255U, 0U, 255U, 255U};
2902 printPreviewText(playlist_description, 10, y, playlist_color);
2903 y += line_height;
2904 }
2905
2906 const std::vector<fs::path> *passes = activePasses();
2907 if (passes != nullptr && !passes->empty()) {
2908 constexpr std::size_t MAX_HUD_PASS_LINES = 8U;
2909 const std::size_t displayed_passes = std::min(passes->size(), MAX_HUD_PASS_LINES);
2910 for (std::size_t index = 0; index < displayed_passes; ++index) {
2911 std::ostringstream pass;
2912 pass << "Pass [" << (index + 1) << '/' << passes->size() << "]: " << (*passes)[index].filename().string();
2913 printPreviewText(clipOverlayText(pass.str()), 10, y, shader_color);
2914 y += line_height;
2915 }
2916 if (displayed_passes < passes->size()) {
2917 const std::string remaining = "Passes: +" + std::to_string(passes->size() - displayed_passes) + " more";
2918 printPreviewText(remaining, 10, y, shader_color);
2919 y += line_height;
2920 }
2921 }
2922
2923 if (model_initialized) {
2924 const SDL_Color model_color{0U, 220U, 180U, 255U};
2925 std::string model_status = model_3d_active ? "Model: " : "Model (2D bypass): ";
2926 model_status += fs::path(options.model_file).filename().string();
2927 if (model_wave_active) {
2928 model_status += " [wave]";
2929 }
2931 model_status += " [oscillate]";
2932 }
2933 printPreviewText(clipOverlayText(std::move(model_status)), 10, y, model_color);
2934 y += line_height;
2935 }
2936
2937#ifdef ACMXVK_WITH_DNN
2938 const SDL_Color dnn_color{64U, 220U, 128U, 255U};
2939 if (human_segmenter != nullptr) {
2940 printPreviewText(options.human_background ? "DNN: PP-HumanSeg [background]" : "DNN: PP-HumanSeg [foreground]", 10, y, dnn_color);
2941 y += line_height;
2942 }
2943 if (edge_detector != nullptr) {
2944 printPreviewText("DNN: DexiNed edge", 10, y, dnn_color);
2945 y += line_height;
2946 }
2947 if (generic_onnx_processor != nullptr) {
2948 printPreviewText(clipOverlayText("DNN: ONNX " + fs::path(options.onnx_configuration).filename().string()), 10, y, dnn_color);
2949 y += line_height;
2950 }
2951#endif
2952
2953#ifdef AUDIO_ENABLED
2954 if (file_audio_source != nullptr && file_audio_source->is_open()) {
2955 const std::string track = fs::path(file_audio_source->current_track_path()).filename().string();
2956 if (!track.empty()) {
2957 const SDL_Color track_color{255U, 0U, 255U, 255U};
2958 printPreviewText(clipOverlayText("Track: " + track), 10, y, track_color);
2959 y += line_height;
2960 }
2961 }
2962#endif
2963
2964#ifdef ACMXVK_WITH_CUDA
2965 if (gpu_filter_engine != nullptr) {
2966 const SDL_Color gpu_color{255U, 0U, 255U, 255U};
2967 printPreviewText(clipOverlayText("GPU: " + gpu_filter_engine->active_filter_description()), 10, y, gpu_color);
2968 y += line_height;
2969 }
2970#endif
2971
2972 if (autopilot_enabled) {
2973 const int remaining = std::max(0, autopilot_interval_frames - autopilot_counter);
2974 std::ostringstream status;
2975 status << "Autopilot " << (autopilot_sequential ? "seq" : "rnd") << ' ';
2976 if (options.autopilot_random_timeout > 0) {
2977 status << "[4-" << options.autopilot_random_timeout << "] cur=" << autopilot_interval_frames;
2978 } else {
2979 status << "every " << autopilot_interval_frames << 'f';
2980 }
2981 status << " next=" << remaining << "f";
2982 if (!playlist.empty()) {
2983 status << " idx=" << (playlist_index + 1) << '/' << playlist.size();
2984 }
2985 const SDL_Color autopilot_color{0U, 255U, 255U, 255U};
2986 printPreviewText(clipOverlayText(status.str()), 10, y, autopilot_color);
2987 y += line_height;
2988 }
2989
2990 const SDL_Color status_color{255U, 255U, 255U, 255U};
2992 printPreviewText(hudVideoTimeString(), 10, y, status_color);
2993 y += line_height;
2994 }
2995 printPreviewText(hudElapsedTimeString(), 10, y, status_color);
2996 y += line_height;
2997 if (writer.is_open()) {
2998 const double duration_seconds = recording_fps > 0.0 ? static_cast<double>(output_frame_count) / recording_fps : writer.get_duration();
2999 const std::string bitrate = format_bitrate(writer.get_bytes_written(), duration_seconds);
3000 if (!bitrate.empty()) {
3001 printPreviewText("Bitrate: " + bitrate, 10, y, status_color);
3002 y += line_height;
3003 }
3004 }
3005 std::ostringstream fps;
3006 fps << "Render: " << std::fixed << std::setprecision(1) << hud_display_fps << " FPS";
3007 printPreviewText(fps.str(), 10, y, status_color);
3008 y += line_height;
3010 std::ostringstream camera_fps;
3011 camera_fps << "Camera: ";
3012 if (camera_delivered_fps > 0.0) {
3013 camera_fps << std::fixed << std::setprecision(1) << camera_delivered_fps << " FPS measured";
3014 } else {
3015 camera_fps << "measuring...";
3016 }
3017 printPreviewText(camera_fps.str(), 10, y, status_color);
3018 y += line_height;
3019 }
3020 const SDL_Color hint_color{128U, 128U, 128U, 255U};
3021 printPreviewText("F9: Toggle overlay", 10, y, hint_color);
3022 y += line_height;
3023 }
3024
3026 if (counter_disabled && !options.display_filter && (!watermark_enabled || options.watermark_text.empty())) {
3027 return;
3028 }
3029
3030 constexpr int LEFT_MARGIN = 10;
3031 constexpr int TOP_MARGIN = 10;
3032 const int line_height = overlay_font_size + 4;
3033 const int preview_line_height = preview_overlay_font_size + 4;
3034 int preview_y = TOP_MARGIN + (!counter_disabled && watermark_enabled && !options.watermark_text.empty() ? preview_line_height : 0);
3035 queueRuntimeHud(preview_y, preview_line_height);
3036 int y = TOP_MARGIN;
3037 if (options.display_filter) {
3038 const SDL_Color filter_color{255U, 0U, 255U, 255U};
3039 std::string shader = effects_enabled ? fs::path(currentShader()).filename().string() : "bypassed";
3040 printText(clipOverlayText(std::string(activeShaderRole()) + ": " + std::move(shader)), LEFT_MARGIN, y, filter_color);
3041 y += line_height;
3042
3043 if (playlist_enabled && !playlist.empty()) {
3044 printText(clipOverlayText("Playlist: " + playlist[playlist_index].name), LEFT_MARGIN, y, filter_color);
3045 y += line_height;
3046 }
3047 const std::string passes = activePassDescription();
3048 if (!passes.empty()) {
3049 printText(passes, LEFT_MARGIN, y, filter_color);
3050 y += line_height;
3051 }
3052#ifdef ACMXVK_WITH_CUDA
3053 if (gpu_filter_engine != nullptr) {
3054 printText(clipOverlayText("GPU: " + gpu_filter_engine->active_filter_description()), LEFT_MARGIN, y, filter_color);
3055 y += line_height;
3056 }
3057#endif
3058 }
3059
3060 if (watermark_enabled && !options.watermark_text.empty()) {
3061 const SDL_Color watermark_color{options.watermark_color[0], options.watermark_color[1], options.watermark_color[2], 255U};
3062 printText(clipOverlayText(options.watermark_text), LEFT_MARGIN, y, watermark_color);
3063 }
3064 }
3065
3066 [[nodiscard]] std::string MainWindow::captureFourccName(double value) {
3067 if (!std::isfinite(value) || value <= 0.0 || value > static_cast<double>(std::numeric_limits<std::uint32_t>::max())) {
3068 return "unknown";
3069 }
3070 const auto fourcc = static_cast<std::uint32_t>(std::llround(value));
3071 std::string name(4, ' ');
3072 for (std::size_t index = 0; index < name.size(); ++index) {
3073 const auto byte = static_cast<unsigned char>((fourcc >> (index * 8U)) & 0xffU);
3074 if (!std::isprint(byte)) {
3075 return "unknown";
3076 }
3077 name[index] = static_cast<char>(byte);
3078 }
3079 return name;
3080 }
3081
3082 [[nodiscard]] bool MainWindow::hostPreprocessingEnabled() const {
3083#ifdef ACMXVK_WITH_STABLE_DIFFUSION
3084 if (stable_diffusion_server != nullptr && !options.stable_diffusion_after_shaders) {
3085 return true;
3086 }
3087#endif
3088#ifdef ACMXVK_WITH_DEEP_DREAM
3089 if (deep_dream_model != nullptr) {
3090 return true;
3091 }
3092#endif
3093#ifdef ACMXVK_WITH_DNN
3094 return edge_detector != nullptr || human_segmenter != nullptr || generic_onnx_processor != nullptr;
3095#else
3096 return false;
3097#endif
3098 }
3099
3101#ifdef ACMXVK_WITH_DEEP_DREAM
3102 if (deep_dream_model == nullptr || !options.random_dream_specified) {
3103 return;
3104 }
3105
3106 double timeline = 0.0;
3107 if (!currentVideoTimeline(timeline)) {
3108 timeline = hudWallElapsedSeconds();
3109 }
3110 if (!std::isfinite(timeline) || timeline < 0.0) {
3111 timeline = 0.0;
3112 }
3114 random_dream_period = std::numeric_limits<std::uint64_t>::max();
3116 }
3118
3119 const auto period = static_cast<std::uint64_t>(std::floor(timeline / options.random_dream_interval));
3120 if (period == random_dream_period) {
3121 return;
3122 }
3123 random_dream_period = period;
3124
3125 std::uniform_int_distribution<int> iterations(1, 3);
3126 std::uniform_real_distribution<double> strength(0.01, 0.05);
3127 std::uniform_real_distribution<double> zoom(0.985, 1.015);
3128 std::uniform_real_distribution<double> rotation_magnitude(0.5, 3.0);
3129 std::uniform_real_distribution<double> octave_scale(1.2, 1.6);
3130 std::uniform_int_distribution<int> rotation_direction(0, 1);
3131 std::uniform_int_distribution<int> octaves(1, 8);
3132 std::uniform_int_distribution<int> jitter(0, 4);
3133 std::uniform_int_distribution<int> smoothing(0, 3);
3134 static constexpr std::array<int, 4> RANDOM_DIMENSIONS = {256, 384, 512, 640};
3135 std::uniform_int_distribution<std::size_t> dimension(0, RANDOM_DIMENSIONS.size() - 1);
3136
3137 if (!options.dream_iterations_specified) {
3138 options.dream_iterations = iterations(random_dream_rng);
3139 }
3140 if (!options.dream_strength_specified) {
3141 options.dream_strength = strength(random_dream_rng);
3142 }
3143 if (!options.dream_zoom_specified) {
3144 options.dream_zoom = zoom(random_dream_rng);
3145 }
3146 if (!options.dream_rotation_specified) {
3147 const double magnitude = rotation_magnitude(random_dream_rng);
3148 options.dream_rotation = rotation_direction(random_dream_rng) == 0 ? -magnitude : magnitude;
3149 }
3150 if (!options.dream_size_specified) {
3151 options.dream_size = RANDOM_DIMENSIONS[dimension(random_dream_rng)];
3152 }
3153 if (!options.dream_octaves_specified) {
3154 options.dream_octaves = octaves(random_dream_rng);
3155 }
3156 if (!options.dream_octave_scale_specified) {
3157 options.dream_octave_scale = octave_scale(random_dream_rng);
3158 }
3159 if (!options.dream_jitter_specified) {
3160 options.dream_jitter = jitter(random_dream_rng);
3161 }
3162 if (!options.dream_smoothing_specified) {
3163 options.dream_smoothing = smoothing(random_dream_rng);
3164 }
3165
3166 std::cout << "acmxvk: random dream settings: iterations " << options.dream_iterations << ", strength " << options.dream_strength << ", zoom " << options.dream_zoom << ", rotation " << options.dream_rotation << ", octaves " << options.dream_octaves << ", octave scale " << options.dream_octave_scale << ", size " << options.dream_size << ", jitter " << options.dream_jitter << ", smoothing " << options.dream_smoothing << '\n';
3167#endif
3168 }
3169
3171#ifdef ACMXVK_WITH_DEEP_DREAM
3172 if (deep_dream_model == nullptr || rgba.empty()) {
3173 return;
3174 }
3175 if (rgba.type() == CV_16UC4) {
3176 cv::Mat compatible = rgba16ToRgba8(rgba);
3178 std::cout << "acmxvk: Deep Dream uses an RGBA8 compatibility "
3179 "copy for HDR input\n";
3181 }
3182 applyDeepDreamEffect(compatible);
3183 compatible.convertTo(rgba, CV_16UC4, 257.0);
3184 return;
3185 }
3188 try {
3189 result = deep_dream_model->apply_gradient_ascent(rgba, dream::GradientAscentOptions{options.dream_iterations, static_cast<float>(options.dream_strength), static_cast<float>(options.dream_feedback), static_cast<float>(options.dream_zoom), static_cast<float>(options.dream_rotation), options.dream_size, options.dream_channel, options.dream_octaves, static_cast<float>(options.dream_octave_scale), options.dream_jitter, options.dream_smoothing});
3190 } catch (const std::exception &error) {
3191 handleDeepDreamRuntimeError(error.what());
3192 return;
3193 }
3194 if (!std::isfinite(result.mean_pixel_change)) {
3195 handleDeepDreamRuntimeError("Deep Dream returned a non-finite processed frame");
3196 return;
3197 }
3199 std::cout << "acmxvk: Deep Dream working frame: " << result.processed_width << 'x' << result.processed_height << " -> " << rgba.cols << 'x' << rgba.rows << " source texture (" << result.processed_octaves << " octave(s))\n";
3201 }
3202#else
3203 static_cast<void>(rgba);
3204#endif
3205 }
3206
3207 void MainWindow::handleDeepDreamRuntimeError(std::string_view message) {
3208#ifdef ACMXVK_WITH_DEEP_DREAM
3209 std::cerr << "acmxvk: Deep Dream frame failed: " << message << "; disabling Deep Dream while keeping ACMXVK running\n";
3210 deep_dream_model.reset();
3211#ifdef ACMXVK_WITH_MXVK_CUDA
3212 cuda_dream_rgba.release();
3213#endif
3214 options.dream_model.clear();
3215 options.dream_layer.clear();
3216 options.gpu_filter_before_dream = false;
3218#else
3219 static_cast<void>(message);
3220#endif
3221 }
3222
3223 void MainWindow::applyDnnEffects(cv::Mat &rgba) {
3224#ifdef ACMXVK_WITH_DNN
3225 if (rgba.type() == CV_16UC4 && (human_segmenter != nullptr || edge_detector != nullptr || generic_onnx_processor != nullptr)) {
3226 cv::Mat compatible = rgba16ToRgba8(rgba);
3228 std::cout << "acmxvk: HDR increment 2: DNN preprocessing uses an "
3229 "RGBA8 compatibility copy before RGBA16 upload\n";
3231 }
3232 applyDnnEffects(compatible);
3233 compatible.convertTo(rgba, CV_16UC4, 257.0);
3234 return;
3235 }
3236 if (human_segmenter != nullptr && !rgba.empty()) {
3237 cv::Mat bgr;
3238 cv::cvtColor(rgba, bgr, cv::COLOR_RGBA2BGR);
3239 const cv::Mat mask = human_segmenter->infer(bgr);
3240 if (mask.empty()) {
3241 throw std::runtime_error("PP-HumanSeg produced an empty person mask");
3242 }
3243 const float black_point = static_cast<float>(options.human_black_point);
3244 const float white_point = static_cast<float>(options.human_white_point);
3245 if (options.human_background) {
3246 const cv::Mat alpha = dnn::hardenedAlphaMask(bgr, mask, black_point, white_point);
3247 cv::cvtColor(bgr, human_overlay_rgba, cv::COLOR_BGR2RGBA);
3248 std::vector<cv::Mat> overlay_channels;
3249 cv::split(human_overlay_rgba, overlay_channels);
3250 alpha.copyTo(overlay_channels[3]);
3251 cv::merge(overlay_channels, human_overlay_rgba);
3252
3253 const cv::Mat foreground = dnn::isolateBody(bgr, mask, black_point, white_point);
3254 cv::Mat background;
3255 cv::subtract(bgr, foreground, background);
3256 cv::cvtColor(background, rgba, cv::COLOR_BGR2RGBA);
3257 } else {
3258 const cv::Mat foreground = dnn::isolateBody(bgr, mask, black_point, white_point);
3259 cv::cvtColor(foreground, rgba, cv::COLOR_BGR2RGBA);
3260 }
3261 }
3262 if (edge_detector != nullptr && !rgba.empty()) {
3263 try {
3264 cv::Mat bgr;
3265 cv::Mat edge;
3266 cv::cvtColor(rgba, bgr, cv::COLOR_RGBA2BGR);
3267 edge_detector->process(bgr, edge);
3268 if (edge.empty()) {
3269 throw std::runtime_error("DexiNed produced an empty edge frame");
3270 }
3271 if (edge.channels() == 1) {
3272 cv::cvtColor(edge, rgba, cv::COLOR_GRAY2RGBA);
3273 } else {
3274 cv::cvtColor(edge, rgba, cv::COLOR_BGR2RGBA);
3275 }
3276 } catch (const std::exception &error) {
3277 std::cerr << "acmxvk: edge inference failed; disabling DNN "
3278 "effect: "
3279 << error.what() << '\n';
3280 edge_detector.reset();
3281 }
3282 }
3283 if (generic_onnx_processor != nullptr && !rgba.empty()) {
3284 try {
3285 cv::Mat bgr;
3286 cv::Mat processed;
3287 cv::cvtColor(rgba, bgr, cv::COLOR_RGBA2BGR);
3288 generic_onnx_processor->process(bgr, processed);
3289 if (processed.empty()) {
3290 throw std::runtime_error("generic ONNX model produced an empty frame");
3291 }
3292 if (processed.channels() == 1) {
3293 cv::cvtColor(processed, rgba, cv::COLOR_GRAY2RGBA);
3294 } else {
3295 cv::cvtColor(processed, rgba, cv::COLOR_BGR2RGBA);
3296 }
3297 } catch (const std::exception &error) {
3298 std::cerr << "acmxvk: generic ONNX inference failed; disabling "
3299 "model: "
3300 << error.what() << '\n';
3301 generic_onnx_processor.reset();
3302 }
3303 }
3304#else
3305 static_cast<void>(rgba);
3306#endif
3307 }
3308
3310#ifdef ACMXVK_WITH_DNN
3311 if (!options.human_background || human_overlay_rgba.empty() || getDevice() == VK_NULL_HANDLE) {
3312 return;
3313 }
3314 if (human_overlay_sprite == nullptr) {
3315 human_overlay_sprite = createSprite(1, 1);
3316 human_overlay_sprite->enableHistoryTexture(static_cast<std::uint32_t>(human_overlay_rgba.cols), static_cast<std::uint32_t>(human_overlay_rgba.rows), 1U);
3317 }
3318 cv::Mat upload = human_overlay_rgba;
3319 cv::Mat flipped;
3320 if (options.flip_output) {
3321 cv::flip(human_overlay_rgba, flipped, 0);
3322 upload = flipped;
3323 }
3324 human_overlay_sprite->updateHistoryTexture(upload.ptr(), upload.cols, upload.rows, static_cast<int>(upload.step));
3325#endif
3326 }
3327 // Input setup, output encoding, snapshots, and readback handling.
3329 if (!options.graphic_file.empty()) {
3331 graphic_rgba = loadRgbaImage(options.graphic_file);
3334 rotateFrame(graphic_rgba, options.frame_rotation);
3335 if (!human_overlay_rgba.empty()) {
3336 rotateFrame(human_overlay_rgba, options.frame_rotation);
3337 }
3338 return;
3339 }
3340
3342 bool opened = false;
3344 opened = openVideoCapture();
3345 } else {
3346 opened = capture.open(options.camera_device);
3347 }
3348 if (!opened) {
3349 const std::string source = source_kind == SourceKind::Video ? options.input_file : std::to_string(options.camera_device);
3350 throw std::runtime_error("unable to open capture source: " + source);
3351 }
3352
3356#ifdef MXVK_WITH_FFMPEG_CAPTURE
3357 hdr_input_precision_enabled = video_hdr_info.valid && video_hdr_info.hdr && using_ffmpeg_capture;
3358#else
3360#endif
3361 if (options.gpu_filter_before_dream && hdr_input_precision_enabled) {
3362 throw std::runtime_error("--gpu-filter-before-dream does not support HDR input");
3363 }
3364 hdr_transfer_processing_enabled = hdr_input_precision_enabled && (video_hdr_info.color_transfer == COLOR_TRANSFER_SMPTE2084 || video_hdr_info.color_transfer == COLOR_TRANSFER_ARIB_STD_B67);
3365 hdr_transfer_hlg = video_hdr_info.color_transfer == COLOR_TRANSFER_ARIB_STD_B67;
3366 setHdrRenderIntermediatesEnabled(hdr_input_precision_enabled);
3367 setFrameReadbackRgba16Enabled(hdr_input_precision_enabled);
3368 std::ostringstream timeline;
3369 timeline << "acmxvk: video timeline: " << std::fixed << std::setprecision(3) << video_source_fps << " FPS";
3370 if (video_duration_seconds > 0.0) {
3371 timeline << ", " << video_duration_seconds << " seconds";
3372 } else {
3373 timeline << ", duration unavailable";
3374 }
3375 std::cout << timeline.str() << '\n';
3376 if (video_hdr_info.valid && video_hdr_info.hdr) {
3377 std::cout << "acmxvk: HDR input metadata detected\n";
3380 std::cout << "acmxvk: HDR processing active: native "
3381 "RGBA16 input, RGBA16F effects/history, and "
3382 "normalized RGBA16 Vulkan readback\n";
3384 std::cout << "acmxvk: HDR transfer: " << (hdr_transfer_hlg ? "HLG" : "PQ")
3385 << " decoded to linear BT.2020 before effects and "
3386 "encoded after effects\n";
3387 if (!options.headless) {
3388 std::cout << "acmxvk: HDR preview: presentation-only "
3389 "BT.2020-to-BT.709 SDR tone mapping active; "
3390 "Main10 recording remains unchanged\n";
3391 }
3392 } else {
3393 std::cerr << "acmxvk: HDR transfer " << video_hdr_info.color_transfer
3394 << " is not PQ or HLG; preserving transfer-encoded "
3395 "values through the precision path\n";
3396 }
3397 } else {
3398 std::cout << "acmxvk: HDR precision path unavailable because this "
3399 "build is not using MXVK FFmpeg capture; falling "
3400 "back to RGBA8\n";
3401 }
3402 }
3403 if (options.use_source_fps) {
3404 std::cout << "acmxvk: source-FPS playback enabled at " << video_source_fps << " FPS; early frames wait and late frames are skipped\n";
3405 }
3406 }
3407
3409 // Match ACMX2's ordering. Some V4L2 drivers renegotiate the
3410 // frame interval when dimensions or pixel format change.
3411 capture.set(cv::CAP_PROP_BUFFERSIZE, 1.0);
3412 capture.set(cv::CAP_PROP_FRAME_WIDTH, options.camera_width);
3413 capture.set(cv::CAP_PROP_FRAME_HEIGHT, options.camera_height);
3414 const int requested_fourcc = options.use_yuv ? cv::VideoWriter::fourcc('Y', 'U', 'Y', 'V') : cv::VideoWriter::fourcc('M', 'J', 'P', 'G');
3415 capture.set(cv::CAP_PROP_FOURCC, static_cast<double>(requested_fourcc));
3416 if (options.requested_fps > 0.0) {
3417 capture.set(cv::CAP_PROP_FPS, options.requested_fps);
3418 }
3419
3420 camera_reported_width = static_cast<int>(std::lround(capture.get(cv::CAP_PROP_FRAME_WIDTH)));
3421 camera_reported_height = static_cast<int>(std::lround(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));
3422 camera_reported_fps = capture.get(cv::CAP_PROP_FPS);
3423 if (!std::isfinite(camera_reported_fps) || camera_reported_fps < 0.0) {
3424 camera_reported_fps = 0.0;
3425 }
3426 const std::string reported_fourcc = captureFourccName(capture.get(cv::CAP_PROP_FOURCC));
3427
3428 std::cout << "acmxvk: camera opened: " << camera_reported_width << 'x' << camera_reported_height;
3429 if (camera_reported_fps > 0.0) {
3430 std::cout << " at reported " << camera_reported_fps << " FPS";
3431 } else {
3432 std::cout << " at an unreported frame rate";
3433 }
3434 std::cout << ", format=" << reported_fourcc << '\n';
3435
3436 if (camera_reported_width != options.camera_width || camera_reported_height != options.camera_height) {
3437 std::cerr << "acmxvk: camera mode warning: requested " << options.camera_width << 'x' << options.camera_height << " but driver reports " << camera_reported_width << 'x' << camera_reported_height << '\n';
3438 }
3439 if (options.requested_fps > 0.0 && camera_reported_fps > 0.0 && std::abs(camera_reported_fps - options.requested_fps) > 0.05) {
3440 std::cerr << "acmxvk: camera mode warning: requested " << options.requested_fps << " FPS but driver reports " << camera_reported_fps << " FPS\n";
3441 }
3442 const std::string requested_format = options.use_yuv ? "YUYV" : "MJPG";
3443 if (reported_fourcc != "unknown" && reported_fourcc != requested_format) {
3444 std::cerr << "acmxvk: camera mode warning: requested " << requested_format << " but driver reports " << reported_fourcc << '\n';
3445 }
3446 if (options.maximize_fps) {
3448 std::cout << "acmxvk: maximize FPS active: asynchronous camera "
3449 "capture, Vulkan render target "
3450 << options.requested_fps << " FPS\n";
3451 if (options.enable_vsync) {
3452 std::cout << "acmxvk: maximize FPS note: VSync may cap the "
3453 "render rate to the display refresh\n";
3454 }
3455 }
3456 }
3457 }
3458
3459 [[nodiscard]] std::pair<int, int> MainWindow::source_dimensions() {
3460 int source_width = options.width;
3461 int source_height = options.height;
3463 source_width = graphic_rgba.cols;
3464 source_height = graphic_rgba.rows;
3465 } else {
3466#ifdef MXVK_WITH_FFMPEG_CAPTURE
3467 if (using_ffmpeg_capture) {
3468 source_width = ffmpeg_capture.width();
3469 source_height = ffmpeg_capture.height();
3470 } else
3471#endif
3472 {
3474 source_width = camera_reported_width;
3475 source_height = camera_reported_height;
3476 } else {
3477 source_width = static_cast<int>(std::lround(capture.get(cv::CAP_PROP_FRAME_WIDTH)));
3478 source_height = static_cast<int>(std::lround(capture.get(cv::CAP_PROP_FRAME_HEIGHT)));
3479 }
3480 }
3481 if (source_width <= 0 || source_height <= 0) {
3482 source_width = source_kind == SourceKind::Camera ? options.camera_width : options.width;
3483 source_height = source_kind == SourceKind::Camera ? options.camera_height : options.height;
3484 }
3485 if (rotationSwapsDimensions(options.frame_rotation)) {
3486 std::swap(source_width, source_height);
3487 }
3488 }
3489 return {source_width, source_height};
3490 }
3491
3493 int render_width = options.width;
3494 int render_height = options.height;
3495 if (!options.resolution_specified) {
3496 const auto [source_width, source_height] = source_dimensions();
3497 if (!dimensions_supported(source_width, source_height)) {
3498 throw std::runtime_error("input source dimensions are outside the supported range");
3499 }
3500
3501 render_width = source_width;
3502 render_height = source_height;
3503 options.width = render_width;
3504 options.height = render_height;
3505 const char *source_name = source_kind == SourceKind::Video ? "video" : source_kind == SourceKind::Camera ? "camera" : "graphic";
3506 std::cout << "acmxvk: automatic output resolution: " << render_width << 'x' << render_height << " from " << source_name;
3507 if (rotationSwapsDimensions(options.frame_rotation)) {
3508 std::cout << " after input rotation";
3509 }
3510 std::cout << '\n';
3511 } else {
3512 std::cout << "acmxvk: requested output resolution: " << render_width << 'x' << render_height << '\n';
3513 }
3514 setRenderExtent(static_cast<std::uint32_t>(render_width), static_cast<std::uint32_t>(render_height));
3515
3516 if (options.headless) {
3517 std::cout << "acmxvk: headless output resolution: " << render_width << 'x' << render_height << '\n';
3518 return;
3519 }
3520
3521 if (options.fullscreen) {
3522 std::cout << "acmxvk: fullscreen presentation uses the display "
3523 "extent without changing the output resolution\n";
3524 return;
3525 }
3526
3527 SDL_Window *window = getSDLWindow();
3528 if (window == nullptr) {
3529 throw std::runtime_error("unable to configure preview without an SDL window");
3530 }
3531
3532 int preview_width = render_width;
3533 int preview_height = render_height;
3534 SDL_Rect usable_bounds{};
3535 SDL_DisplayID display = SDL_GetDisplayForWindow(window);
3536 if (display == 0) {
3537 display = SDL_GetPrimaryDisplay();
3538 }
3539 if (display != 0 && SDL_GetDisplayUsableBounds(display, &usable_bounds) && usable_bounds.w > 0 && usable_bounds.h > 0) {
3540 constexpr double PREVIEW_DISPLAY_FRACTION = 0.9;
3541 const double width_scale = (static_cast<double>(usable_bounds.w) * PREVIEW_DISPLAY_FRACTION) / render_width;
3542 const double height_scale = (static_cast<double>(usable_bounds.h) * PREVIEW_DISPLAY_FRACTION) / render_height;
3543 const double preview_scale = std::min({1.0, width_scale, height_scale});
3544 preview_width = std::max(1, static_cast<int>(std::lround(render_width * preview_scale)));
3545 preview_height = std::max(1, static_cast<int>(std::lround(render_height * preview_scale)));
3546 }
3547
3548 const float render_aspect = static_cast<float>(render_width) / static_cast<float>(render_height);
3549 if (!SDL_SetWindowAspectRatio(window, render_aspect, render_aspect)) {
3550 std::cerr << "acmxvk: unable to lock preview aspect ratio: " << SDL_GetError() << '\n';
3551 }
3552 if (!SDL_SetWindowSize(window, preview_width, preview_height)) {
3553 throw std::runtime_error(std::string("unable to apply preview resolution: ") + SDL_GetError());
3554 }
3555 SDL_SetWindowPosition(window, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED);
3556 if (!SDL_SyncWindow(window)) {
3557 std::cerr << "acmxvk: window resize sync warning: " << SDL_GetError() << '\n';
3558 }
3559
3560 int actual_width = 0;
3561 int actual_height = 0;
3562 SDL_GetWindowSizeInPixels(window, &actual_width, &actual_height);
3563 std::cout << "acmxvk: preview resolution: " << actual_width << 'x' << actual_height;
3564 if (preview_width != render_width || preview_height != render_height) {
3565 std::cout << " (" << render_width << 'x' << render_height << " output, preview fitted to display)";
3566 }
3567 std::cout << '\n';
3568 }
3569
3570 [[nodiscard]] double MainWindow::outputFrameRate() {
3571 if (options.requested_fps > 0.0) {
3572 return options.requested_fps;
3573 }
3575 double source_fps = 0.0;
3576#ifdef MXVK_WITH_FFMPEG_CAPTURE
3577 if (using_ffmpeg_capture) {
3578 source_fps = ffmpeg_capture.fps();
3579 } else
3580#endif
3581 {
3582 source_fps = capture.get(cv::CAP_PROP_FPS);
3583 }
3584 if (std::isfinite(source_fps) && source_fps > 0.0) {
3585 return source_fps;
3586 }
3587 }
3588 return 30.0;
3589 }
3590
3592#ifndef ACMXVK_WITH_TIFF
3593 if (format == SnapshotFormat::Tiff) {
3594 std::cerr << "acmxvk: TIFF snapshots require a build configured "
3595 "with -DTIFF=ON\n";
3596 return;
3597 }
3598#endif
3599#ifndef ACMXVK_WITH_WEBP
3600 if (format == SnapshotFormat::WebP) {
3601 std::cerr << "acmxvk: WebP snapshots require a build configured "
3602 "with -DWEBP=ON\n";
3603 return;
3604 }
3605#endif
3606 if (snapshot_pending) {
3607 return;
3608 }
3609 if (snapshot_writer.queueFull()) {
3610 std::cerr << "acmxvk: snapshot queue is full; request ignored\n";
3611 return;
3612 }
3613 std::error_code error;
3614 const fs::path directory(options.snapshot_directory);
3615 fs::create_directories(directory, error);
3616 if (error || !fs::is_directory(directory)) {
3617 std::cerr << "acmxvk: unable to create snapshot directory: " << directory.string() << '\n';
3618 return;
3619 }
3620 if (!snapshot_writer.start()) {
3621 return;
3622 }
3623 snapshot_pending = true;
3624 pending_snapshot_format = format;
3625 setFrameReadbackEnabled(true);
3626 std::cout << "acmxvk: " << SnapshotWriter::formatName(format) << " snapshot requested\n";
3627 }
3628
3629 [[nodiscard]] bool MainWindow::continuousReadbackEnabled() const { return writer.is_open() || options.png_output || options.generate_interval > 0; }
3630
3632 if (options.output_file.empty() && !options.png_output && options.generate_interval <= 0) {
3633 return;
3634 }
3635
3636 const VkExtent2D extent = getRenderExtent();
3637 if (options.resolution_specified) {
3638 recording_width = extent.width > 0U ? static_cast<int>(extent.width) : options.width;
3639 recording_height = extent.height > 0U ? static_cast<int>(extent.height) : options.height;
3640 } else {
3641 recording_width = options.width;
3642 recording_height = options.height;
3643 }
3645
3646 if (options.png_output) {
3647 png_output_directory = options.png_output_directory;
3649 const int png_interval = std::max(1, options.generate_interval);
3650 std::cout << "acmxvk: writing PNG sequence to " << png_output_directory.string();
3651 if (png_interval > 1) {
3652 std::cout << " (every " << png_interval << "th frame)";
3653 }
3654 std::cout << '\n';
3655 }
3656
3657 if (!options.output_file.empty() && !options.png_output) {
3658 EncodeOptions encode_options;
3659 encode_options.preset = options.encode_preset;
3660 encode_options.tune = options.encode_tune;
3661 encode_options.crf = options.encode_crf;
3662 encode_options.bit_rate = options.encode_bitrate;
3663 encode_options.codec = options.encode_codec;
3664 encode_options.ffmpeg_options = options.encode_params;
3665 encode_options.realtime = options.encode_realtime;
3666 encode_options.block_when_full = options.no_drop || options.fill_pts_gaps;
3668 if (hdr_output_enabled) {
3669 if ((recording_width & 1) != 0 || (recording_height & 1) != 0) {
3670 throw std::runtime_error("HDR Main10 output requires even width and height");
3671 }
3672 encode_options.hdr.enabled = true;
3673 encode_options.hdr.color_primaries = video_hdr_info.color_primaries;
3674 encode_options.hdr.color_trc = video_hdr_info.color_transfer;
3675 encode_options.hdr.color_space = video_hdr_info.color_space;
3676 encode_options.hdr.color_range = video_hdr_info.color_range;
3677 encode_options.hdr.mastering_display = video_hdr_info.mastering_display;
3678 encode_options.hdr.content_light = video_hdr_info.content_light;
3679 std::cout << "acmxvk: HDR output: HEVC Main10 with captured " << (hdr_transfer_hlg ? "BT.2020/HLG" : "BT.2020/PQ") << " color metadata (software libx265)\n";
3680 }
3681
3682 if (options.encode_bitrate > 0) {
3683 std::cout << "acmxvk: encoder rate control: target VBR " << options.encode_bitrate << " bits/s\n";
3684 } else {
3685 std::cout << "acmxvk: encoder rate control: CRF/CQ " << options.encode_crf << '\n';
3686 }
3687
3688 if (!writer.open(options.output_file, recording_width, recording_height, static_cast<float>(recording_fps), encode_options)) {
3689 throw std::runtime_error("unable to open output video: " + options.output_file);
3690 }
3691 writer.set_block_when_full(options.no_drop || options.fill_pts_gaps);
3692 std::cout << "acmxvk: recording " << recording_width << 'x' << recording_height << " at " << recording_fps << " FPS to " << options.output_file << (options.no_drop ? " (no-drop)\n" : "\n");
3693 if (options.constant_frame_rate) {
3694 std::cout << "acmxvk: constant-frame-rate encoding active; rendered "
3695 "video frames use sequential output timestamps\n";
3696 }
3697 if (options.fill_pts_gaps) {
3698 std::cout << "acmxvk: PTS gap filling active; held frames will be "
3699 "duplicated for editing-compatible constant frame rate\n";
3700 }
3701 if (options.mute_output) {
3702 std::cout << "acmxvk: recorded video audio disabled (--mute-output); "
3703 "reactivity and pass-through remain active\n";
3704 }
3705 }
3706
3707 setFrameReadbackEnabled(true);
3708 }
3709
3711 ReadbackRequest request;
3712 request.snapshot = snapshot_pending;
3713 request.snapshot_format = pending_snapshot_format;
3714 request.continuous = continuousReadbackEnabled();
3715 request.frame_due = recording_frame_due;
3716 request.has_pts = recording_frame_has_pts && !options.constant_frame_rate;
3717 request.pts = recording_frame_pts;
3718 readback_requests.push_back(request);
3719
3720 if (snapshot_pending) {
3721 snapshot_pending = false;
3722 if (!request.continuous) {
3723 setFrameReadbackEnabled(false);
3724 }
3725 }
3726 }
3727
3728 void MainWindow::onFrameReadback(std::vector<std::uint8_t> &rgba, uint32_t width, uint32_t height) { handleFrameReadback(rgba, nullptr, width, height); }
3729
3730 void MainWindow::handleFrameReadback(std::vector<std::uint8_t> &rgba, const std::vector<std::uint16_t> *rgba16, uint32_t width, uint32_t height) {
3731 if (readback_requests.empty()) {
3732 std::cerr << "acmxvk: received frame readback without queued metadata\n";
3733 return;
3734 }
3735 const ReadbackRequest request = readback_requests.front();
3736 readback_requests.pop_front();
3737
3738 if (request.snapshot) {
3739 const fs::path path = snapshot_path(options.snapshot_directory, width, height, snapshot_count, request.snapshot_format);
3740 SnapshotJob job;
3741 job.path = path;
3742 job.width = width;
3743 job.height = height;
3744 job.png_level = options.png_level;
3745 job.format = request.snapshot_format;
3746 if (rgba16 != nullptr && (request.snapshot_format == SnapshotFormat::Tiff || request.snapshot_format == SnapshotFormat::Raw)) {
3747 job.rgba16 = *rgba16;
3748 }
3749 if (request.continuous) {
3750 job.rgba = rgba;
3751 } else {
3752 job.rgba = std::move(rgba);
3753 }
3754 snapshot_writer.enqueue(std::move(job));
3756 std::cout << "acmxvk: queued " << SnapshotWriter::formatName(request.snapshot_format) << " snapshot: " << path.string() << '\n';
3757 }
3758
3759 if (!request.continuous || recording_complete || !request.frame_due) {
3760 return;
3761 }
3762
3763 std::uint8_t *output_pixels = rgba.data();
3764 cv::Mat resized;
3765 const std::uint16_t *hdr_output_pixels = rgba16 != nullptr ? rgba16->data() : nullptr;
3766 cv::Mat hdr_resized;
3767 if (static_cast<int>(width) != recording_width || static_cast<int>(height) != recording_height) {
3768 const cv::Mat source(static_cast<int>(height), static_cast<int>(width), CV_8UC4, rgba.data());
3769 cv::resize(source, resized, cv::Size(recording_width, recording_height), 0.0, 0.0, cv::INTER_LINEAR);
3770 output_pixels = resized.ptr();
3771 if (rgba16 != nullptr) {
3772 const cv::Mat hdr_source(static_cast<int>(height), static_cast<int>(width), CV_16UC4, const_cast<std::uint16_t *>(rgba16->data()));
3773 cv::resize(hdr_source, hdr_resized, cv::Size(recording_width, recording_height), 0.0, 0.0, cv::INTER_LINEAR);
3774 hdr_output_pixels = hdr_resized.ptr<std::uint16_t>();
3775 }
3776 }
3777
3778#ifdef ACMXVK_WITH_STABLE_DIFFUSION
3779 cv::Mat stable_diffusion_output;
3780 if (stable_diffusion_server != nullptr && options.stable_diffusion_after_shaders) {
3781 const cv::Mat source(recording_height, recording_width, CV_8UC4, output_pixels);
3782 stable_diffusion_output = stable_diffusion_server->process(source);
3783 if (stable_diffusion_output.empty() || stable_diffusion_output.type() != CV_8UC4 || stable_diffusion_output.cols != recording_width || stable_diffusion_output.rows != recording_height) {
3784 throw std::runtime_error("Stable Diffusion returned an incompatible output frame");
3785 }
3786 output_pixels = stable_diffusion_output.ptr<std::uint8_t>();
3787 }
3788#endif
3789
3790 if (writer.is_open()) {
3791 if (hdr_output_enabled && hdr_output_pixels == nullptr) {
3792 throw std::runtime_error("HDR Main10 recording did not receive an RGBA16 "
3793 "Vulkan readback");
3794 }
3795
3796 const auto write_sequential_frame = [this](std::uint8_t *rgba_pixels, const std::uint16_t *rgba16_pixels) {
3797 if (hdr_output_enabled) {
3798 writer.write_hdr_rgba16(const_cast<std::uint16_t *>(rgba16_pixels));
3799 } else {
3800 writer.write(rgba_pixels);
3801 }
3802 };
3803
3804 if (options.fill_pts_gaps && request.has_pts && request.pts >= gap_fill_next_pts) {
3805 while (gap_fill_next_pts < request.pts) {
3807 write_sequential_frame(gap_fill_previous_rgba.data(), hdr_output_enabled ? gap_fill_previous_rgba16.data() : nullptr);
3808 } else {
3809 write_sequential_frame(output_pixels, hdr_output_pixels);
3810 }
3813 }
3814 write_sequential_frame(output_pixels, hdr_output_pixels);
3815 gap_fill_next_pts = request.pts + 1;
3816
3817 const std::size_t pixel_count = static_cast<std::size_t>(recording_width) * static_cast<std::size_t>(recording_height) * 4U;
3818 if (hdr_output_enabled) {
3819 gap_fill_previous_rgba16.assign(hdr_output_pixels, hdr_output_pixels + pixel_count);
3820 } else {
3821 gap_fill_previous_rgba.assign(output_pixels, output_pixels + pixel_count);
3822 }
3824 } else if (options.fill_pts_gaps && !request.has_pts) {
3825 write_sequential_frame(output_pixels, hdr_output_pixels);
3826 } else if (!options.fill_pts_gaps) {
3827 if (hdr_output_enabled) {
3828 if (request.has_pts) {
3829 writer.write_hdr_rgba16_at_pts(const_cast<std::uint16_t *>(hdr_output_pixels), static_cast<std::int64_t>(request.pts));
3830 } else {
3831 writer.write_hdr_rgba16(const_cast<std::uint16_t *>(hdr_output_pixels));
3832 }
3833 } else if (request.has_pts) {
3834 writer.write_at_pts(output_pixels, static_cast<std::int64_t>(request.pts));
3835 } else {
3836 writer.write(output_pixels);
3837 }
3838 }
3839 }
3840 if (options.png_output) {
3841 const int png_interval = std::max(1, options.generate_interval);
3842 if ((png_frame_count % static_cast<std::uint64_t>(png_interval)) == 0U) {
3844 if (png_interval > 1) {
3845 std::cout << "acmxvk: Wrote PNG in sequence: " << generated_frame_count << "/" << png_frame_count << "\n";
3846 }
3848 }
3850 }
3851
3853 emitHeadlessProgress(false);
3854
3855 if (options.duration > 0.0) {
3856 double output_duration = 0.0;
3857 if (request.has_pts) {
3858 output_duration = static_cast<double>(request.pts + 1) / recording_fps;
3859 } else if (writer.is_open()) {
3860 output_duration = writer.get_duration();
3861 } else {
3862 output_duration = static_cast<double>(output_frame_count) / recording_fps;
3863 }
3864 if (output_duration >= options.duration) {
3865 recording_complete = true;
3867 exit();
3868 }
3869 }
3870
3871 if (options.max_size_mb > 0.0 && writer.is_open()) {
3872 const double maximum_bytes = options.max_size_mb * 1024.0 * 1024.0;
3873 if (static_cast<double>(writer.get_bytes_written()) >= maximum_bytes) {
3874 std::cout << "acmxvk: maximum output size reached (" << options.max_size_mb << " MB)\n";
3875 recording_complete = true;
3876 exit();
3877 }
3878 }
3879 }
3880
3881 void MainWindow::onFrameReadbackRgba16(std::vector<std::uint16_t> &rgba, uint32_t width, uint32_t height) {
3882 if (!hdr_readback_logged) {
3883 std::cout << "acmxvk: HDR readback: normalized RGBA16 received from "
3884 "the final Vulkan HDR intermediate"
3885 << (hdr_output_enabled ? "; feeding MXWrite's HEVC Main10 encoder\n" : "; converting to RGBA8 for snapshots/output\n");
3886 hdr_readback_logged = true;
3887 }
3888 std::vector<std::uint8_t> rgba8 = tone_map_hdr_rgba16(rgba, hdr_transfer_hlg);
3889 handleFrameReadback(rgba8, &rgba, width, height);
3890 }
3891 // 3D rendering, crossfades, pipelines, history, and frame uploads.
3893 if (!options.enable_3d || model_initialized) {
3894 return;
3895 }
3896
3897 try {
3898 input_model.enableExtendedFragmentUniforms();
3899 input_model.load(this, options.model_file, "", "", 1.0F);
3900 input_model.setShaders(this, model_vertex_shader_path(options).string(), model_fragment_shader_path(options).string());
3902 input_model.setBackfaceCulling(false);
3903 model_initialized = true;
3904 model_3d_active = true;
3905 model_last_render_time = std::chrono::steady_clock::now();
3906 std::cout << "acmxvk: loaded 3D model: " << options.model_file << " (" << input_model.model().vertices().size() << " vertices, " << input_model.model().indexCount() << " indices; skybox camera centered; view rotation " << (model_auto_rotate ? "enabled" : "disabled") << ")\n";
3907 } catch (...) {
3908 if (getDevice() != VK_NULL_HANDLE) {
3909 vkDeviceWaitIdle(getDevice());
3910 input_model.cleanup(this);
3911 }
3912 throw;
3913 }
3914 }
3915
3917 if (!ensureRenderResources()) {
3918 throw std::runtime_error("MXVK failed to initialize render resources");
3919 }
3920
3921 const auto [source_width, source_height] = source_dimensions();
3922
3923 if (frame_sprite == nullptr) {
3924 frame_sprite = createSprite(source_width, source_height);
3925 }
3926 frame_sprite->enableExtendedUBO();
3927 frame_sprite->setCustomUniforms(custom_uniform_values);
3929 frame_sprite->enableSpectrumTexture(spectrumBinCount());
3930 }
3932 frame_sprite->enableSpectrumHistoryTexture(spectrumBinCount(), static_cast<std::uint32_t>(options.audio_buffers));
3933 }
3934 if (historyCacheEnabled()) {
3935 int history_width = source_width;
3936 int history_height = source_height;
3937 if (options.stable_diffusion_upscale || !options.stable_diffusion_upscale_model.empty()) {
3938 history_width = options.stable_diffusion_width;
3939 history_height = options.stable_diffusion_height;
3940 if (!options.stable_diffusion_upscale_model.empty()) {
3941 history_width = options.width;
3942 history_height = options.height;
3943 }
3944 if (rotationSwapsDimensions(options.frame_rotation)) {
3945 std::swap(history_width, history_height);
3946 }
3947 }
3949 frame_sprite->enableHistoryTextureRgba16Float(history_width, history_height, static_cast<uint32_t>(options.texture_cache_size));
3950 } else {
3951 frame_sprite->enableHistoryTexture(history_width, history_height, static_cast<uint32_t>(options.texture_cache_size));
3952 }
3953 }
3954 const std::string initial_fragment = options.history_test ? echo_cache_shader_path(options).string() : hdr_input_precision_enabled ? passthrough_shader_path(options).string() : std::string{};
3956 frame_sprite->createEmptySpriteRgba16(source_width, source_height, sprite_vertex_shader_path(options).string(), initial_fragment);
3957 } else {
3958 frame_sprite->createEmptySprite(source_width, source_height, sprite_vertex_shader_path(options).string(), initial_fragment);
3959 }
3960
3961 if (options.human_background && human_overlay_sprite == nullptr) {
3962 human_overlay_sprite = createSprite(1, 1);
3963 human_overlay_sprite->enableHistoryTexture(static_cast<std::uint32_t>(source_width), static_cast<std::uint32_t>(source_height), 1U);
3964 const cv::Mat transparent(source_height, source_width, CV_8UC4, cv::Scalar::all(0));
3965 human_overlay_sprite->updateHistoryTexture(transparent.ptr(), transparent.cols, transparent.rows, static_cast<int>(transparent.step));
3966 }
3967
3969
3970#ifdef ACMXVK_WITH_STABLE_DIFFUSION
3971 if (stable_diffusion_initialization_pending) {
3972 stable_diffusion_initial_frame_deferred = true;
3973 } else
3974#endif
3976 initial_frame_pending = false;
3980 } else if (!readTrackedInputFrame()) {
3981 std::cerr << "acmxvk: capture did not provide an initial frame\n";
3982 } else {
3983 initial_frame_pending = true;
3984 }
3985
3987 if (!currentShader().empty()) {
3988 std::cout << "acmxvk: " << activeShaderRole() << ' ' << (shader_index + 1) << '/' << shaders.size() << ": " << currentShader() << '\n';
3989 }
3990 }
3991
3993 previous_frame = std::chrono::steady_clock::now();
3996 shader_time = 0.0;
3997 frame_count = 0;
3998 }
3999
4001 if (options.cross_fade_duration <= 0.0 || frame_count == 0 || getDevice() == VK_NULL_HANDLE) {
4002 crossfade_active = false;
4003 crossfade_alpha = 1.0F;
4005 return;
4006 }
4007
4008 try {
4009 std::vector<std::uint8_t> captured;
4010 std::uint32_t captured_width = 0;
4011 std::uint32_t captured_height = 0;
4012 captureSnapshotPixels(captured, captured_width, captured_height);
4013 const VkExtent2D extent = getRenderExtent();
4014 if (captured.empty() || captured_width == 0U || captured_height == 0U || extent.width == 0U || extent.height == 0U) {
4015 throw std::runtime_error("the previous rendered frame is unavailable");
4016 }
4017
4018 cv::Mat captured_rgba(static_cast<int>(captured_height), static_cast<int>(captured_width), CV_8UC4, captured.data());
4019 cv::Mat previous_rgba;
4020 if (captured_width == extent.width && captured_height == extent.height) {
4021 previous_rgba = captured_rgba;
4022 } else {
4023 const double captured_aspect = static_cast<double>(captured_width) / captured_height;
4024 const double target_aspect = static_cast<double>(extent.width) / extent.height;
4025 cv::Rect crop(0, 0, static_cast<int>(captured_width), static_cast<int>(captured_height));
4026 if (captured_aspect > target_aspect) {
4027 crop.width = std::max(1, static_cast<int>(std::lround(captured_height * target_aspect)));
4028 crop.x = (static_cast<int>(captured_width) - crop.width) / 2;
4029 } else if (captured_aspect < target_aspect) {
4030 crop.height = std::max(1, static_cast<int>(std::lround(captured_width / target_aspect)));
4031 crop.y = (static_cast<int>(captured_height) - crop.height) / 2;
4032 }
4033 cv::resize(captured_rgba(crop), previous_rgba, cv::Size(static_cast<int>(extent.width), static_cast<int>(extent.height)), 0.0, 0.0, cv::INTER_LINEAR);
4034 }
4035
4036 if (crossfade_previous_sprite == nullptr) {
4037 crossfade_previous_sprite = createSprite(1, 1);
4038 }
4040 crossfade_previous_sprite->enableHistoryTextureRgba16Float(extent.width, extent.height, 1U);
4041 } else {
4042 crossfade_previous_sprite->enableHistoryTexture(extent.width, extent.height, 1U);
4043 }
4045 const cv::Mat linear_previous = decode_hdr_transfer(previous_rgba, hdr_transfer_hlg);
4046 crossfade_previous_sprite->updateHistoryTextureRgba16(linear_previous.ptr<std::uint16_t>(), static_cast<int>(extent.width), static_cast<int>(extent.height), static_cast<int>(linear_previous.step));
4047 } else {
4048 crossfade_previous_sprite->updateHistoryTexture(previous_rgba.ptr(), static_cast<int>(extent.width), static_cast<int>(extent.height), static_cast<int>(previous_rgba.step));
4049 }
4050 crossfade_alpha = 0.0F;
4051 crossfade_active = true;
4052 crossfade_start_time = std::chrono::steady_clock::now();
4054 } catch (const std::exception &error) {
4055 crossfade_active = false;
4056 crossfade_alpha = 1.0F;
4058 std::cerr << "acmxvk: crossfade snapshot unavailable: " << error.what() << "; switching immediately\n";
4059 }
4060 }
4061
4062 void MainWindow::updateCrossfade(const std::chrono::steady_clock::time_point now) {
4063 if (!crossfade_active) {
4064 return;
4065 }
4066 double elapsed = 0.0;
4067 double video_timeline = 0.0;
4068 if (crossfade_uses_video_timeline && currentVideoTimeline(video_timeline)) {
4069 if (video_timeline < crossfade_start_video_timeline) {
4070 crossfade_start_video_timeline = video_timeline;
4071 }
4072 elapsed = video_timeline - crossfade_start_video_timeline;
4073 } else {
4074 elapsed = std::chrono::duration<double>(now - crossfade_start_time).count();
4075 }
4076 crossfade_alpha = static_cast<float>(std::clamp(elapsed / options.cross_fade_duration, 0.0, 1.0));
4077 if (crossfade_alpha >= 1.0F) {
4078 crossfade_active = false;
4081 }
4082 }
4083
4084 void MainWindow::cycleCrossfade(int direction) {
4085 const auto count = static_cast<std::ptrdiff_t>(CROSSFADE_NAMES.size());
4086 auto index = static_cast<std::ptrdiff_t>(crossfade_shader_index) + direction;
4087 index = (index % count + count) % count;
4088 crossfade_shader_index = static_cast<std::size_t>(index);
4089 std::cout << "acmxvk: crossfade shader: " << CROSSFADE_NAMES[crossfade_shader_index] << " (" << (crossfade_shader_index + 1) << '/' << CROSSFADE_NAMES.size() << ")\n";
4090 }
4091
4092 void MainWindow::adjustModelScale(float amount) {
4094 return;
4095 }
4096 model_scale = std::clamp(model_scale + amount, 0.05F, 20.0F);
4097 std::cout << "acmxvk: model scale " << model_scale << '\n';
4098 }
4099
4102 return;
4103 }
4104 std::uniform_int_distribution<std::size_t> distribution(0, CROSSFADE_NAMES.size() - 1);
4105 std::size_t next = distribution(autopilot_rng);
4106 if (CROSSFADE_NAMES.size() > 1 && next == crossfade_shader_index) {
4107 next = (next + 1) % CROSSFADE_NAMES.size();
4108 }
4110 }
4111
4114 std::cout << "acmxvk: pause is available for video and graphic input\n";
4115 return;
4116 }
4119 std::cout << "acmxvk: input pause " << (input_paused ? "enabled" : "disabled") << '\n';
4120 }
4121
4124 std::cout << "acmxvk: freeze is available for video and graphic input\n";
4125 return;
4126 }
4129 previous_frame = std::chrono::steady_clock::now();
4130 std::cout << "acmxvk: rendering freeze " << (rendering_frozen ? "enabled" : "disabled") << '\n';
4131 }
4132
4133 void MainWindow::stepShaderTime(double amount) {
4134 shader_time += amount;
4135 std::cout << "acmxvk: shader time stepped to " << shader_time << '\n';
4136 }
4137
4138 void MainWindow::adjustTimeSpeed(double amount) {
4139 options.time_speed += amount;
4140 if (std::abs(options.time_speed) < 0.01) {
4141 options.time_speed = 0.0;
4142 }
4143 std::cout << "acmxvk: shader time speed " << options.time_speed << '\n';
4144 }
4145
4147 SDL_Window *window = getSDLWindow();
4148 if (window == nullptr) {
4149 return;
4150 }
4151 const bool fullscreen = (SDL_GetWindowFlags(window) & SDL_WINDOW_FULLSCREEN) != 0;
4152 if (!SDL_SetWindowFullscreen(window, !fullscreen)) {
4153 std::cerr << "acmxvk: unable to toggle fullscreen: " << SDL_GetError() << '\n';
4154 return;
4155 }
4156 std::cout << "acmxvk: fullscreen " << (!fullscreen ? "enabled" : "disabled") << '\n';
4157 }
4158
4160 if (options.autopilot_random_timeout > 0) {
4161 std::uniform_int_distribution<int> distribution(4, std::max(4, options.autopilot_random_timeout));
4163 } else {
4164 autopilot_interval_frames = options.autopilot_frames;
4165 }
4166 }
4167
4168 void MainWindow::logSelectedPlaylistNode(std::string_view action) const {
4169 if (playlist.empty()) {
4170 return;
4171 }
4172 std::cout << "acmxvk: " << action << " playlist node " << (playlist_index + 1) << '/' << playlist.size() << ": " << playlist[playlist_index].name << " (" << playlist[playlist_index].shaders.size() << " passes)\n";
4173 }
4174
4175 [[nodiscard]] std::uint64_t MainWindow::autopilotFrameAdvance() {
4176 double video_timeline = 0.0;
4177 std::uint64_t video_frame_index = 0U;
4178 if (!currentVideoTimeline(video_timeline, &video_frame_index)) {
4180 return 1U;
4181 }
4182
4184 previous_autopilot_video_frame = video_frame_index;
4186 return 1U;
4187 }
4188
4189 const std::uint64_t advance = video_frame_index - previous_autopilot_video_frame;
4190 previous_autopilot_video_frame = video_frame_index;
4191 return advance;
4192 }
4193
4194 void MainWindow::toggleAutopilot(bool sequential) {
4195 if (!playlist_enabled) {
4196 std::cout << "acmxvk: " << (sequential ? "sequential autopilot" : "autopilot") << " requires playlist mode (press P first)\n";
4197 return;
4198 }
4199 if (playlist.empty()) {
4200 std::cout << "acmxvk: autopilot has no playlist entries\n";
4201 return;
4202 }
4203
4204 if (autopilot_enabled && autopilot_sequential == sequential) {
4205 autopilot_enabled = false;
4206 autopilot_sequential = false;
4207 std::cout << "acmxvk: autopilot disabled\n";
4208 return;
4209 }
4210
4211 autopilot_enabled = true;
4212 autopilot_sequential = sequential;
4215 if (options.autopilot_random_timeout <= 0 && options.autopilot_frames <= 0) {
4216 options.autopilot_frames = 300;
4217 }
4219 std::cout << "acmxvk: " << (sequential ? "sequential " : "random ") << "autopilot enabled (";
4220 if (options.autopilot_random_timeout > 0) {
4221 std::cout << "random interval 4-" << options.autopilot_random_timeout << ", current " << autopilot_interval_frames;
4222 } else {
4223 std::cout << "every " << autopilot_interval_frames << " frames";
4224 }
4225 std::cout << ")\n";
4226 }
4227
4229 const std::uint64_t frame_advance = autopilotFrameAdvance();
4231 return;
4232 }
4233 const std::uint64_t remaining = static_cast<std::uint64_t>(std::max(0, autopilot_interval_frames - autopilot_counter));
4234 if (frame_advance < remaining) {
4235 autopilot_counter += static_cast<int>(frame_advance);
4236 return;
4237 }
4239
4242 if (autopilot_sequential && options.autopilot_random_timeout <= 0) {
4243 playlist_index = (playlist_index + 1) % playlist.size();
4244 } else {
4245 std::uniform_int_distribution<std::size_t> distribution(0, playlist.size() - 1);
4246 std::size_t next = distribution(autopilot_rng);
4247 if (playlist.size() > 1 && next == playlist_index) {
4248 next = (next + 1) % playlist.size();
4249 }
4250 playlist_index = next;
4251 }
4252
4255 if (options.autopilot_random_timeout > 0) {
4257 }
4258 logSelectedPlaylistNode("autopilot selected");
4259 }
4260
4261 void MainWindow::selectShader(int direction) {
4262 if (shader_locked || shaders.size() < 2 || frame_sprite == nullptr) {
4263 return;
4264 }
4265 const auto count = static_cast<std::ptrdiff_t>(shaders.size());
4267 auto index = static_cast<std::ptrdiff_t>(shader_index) + direction;
4268 index = (index % count + count) % count;
4269 shader_index = static_cast<std::size_t>(index);
4270
4274 std::cout << "acmxvk: " << activeShaderRole() << ' ' << (shader_index + 1) << '/' << shaders.size() << ": " << currentShader() << '\n';
4275 }
4276
4278 if (shader_locked || playlist.empty()) {
4279 return;
4280 }
4281 const auto count = static_cast<std::ptrdiff_t>(playlist.size());
4283 auto index = static_cast<std::ptrdiff_t>(playlist_index) + direction;
4284 index = (index % count + count) % count;
4285 playlist_index = static_cast<std::size_t>(index);
4289 logSelectedPlaylistNode("selected");
4290 }
4291
4292 [[nodiscard]] std::vector<fs::path> MainWindow::activeShaderPipeline() const {
4293 std::vector<fs::path> pipeline;
4294 if (effects_enabled) {
4295 if (playlist_enabled && !playlist.empty()) {
4296 pipeline = playlist[playlist_index].shaders;
4297 } else if (multipass_enabled) {
4298 pipeline = configured_passes;
4299 }
4300 if (!currentShader().empty()) {
4301 pipeline.emplace_back(currentShader());
4302 }
4303 }
4304 if (options.stable_diffusion_upscale) {
4305 pipeline.insert(pipeline.begin(), stable_diffusion_upscale_shader_path(options));
4306 }
4307 if (options.flip_output) {
4308 pipeline.emplace_back(flip_shader_path(options));
4309 }
4310 if (crossfade_active) {
4311 pipeline.emplace_back(crossfade_shader_path(options, crossfade_shader_index));
4312 }
4313 if (pipeline.empty()) {
4314 pipeline.emplace_back(passthrough_shader_path(options));
4315 }
4316 if (options.human_background) {
4317 pipeline.emplace_back(human_composite_shader_path(options));
4318 }
4319 for (fs::path &shader : pipeline)
4320 shader = resolvedShaderPath(shader);
4321 return pipeline;
4322 }
4323
4324 [[nodiscard]] fs::path MainWindow::directModelFragmentShader() const {
4326 return {};
4327 }
4328
4329 const fs::path shader = resolvedShaderPath(currentShader());
4330 const mxvk::ShaderModuleInfo module_info = mxvk::inspect_spirv(mxvk::load_spv(shader.string()));
4331 if (module_info.stage != mxvk::ShaderStage::Fragment || module_info.usesHistoryTexture || module_info.usesSpectrumTexture || module_info.usesSpectrumHistoryTexture) {
4332 return {};
4333 }
4334 return shader;
4335 }
4336
4338 if (getDevice() == VK_NULL_HANDLE) {
4339 return;
4340 }
4341 vkDeviceWaitIdle(getDevice());
4342 detachPostProcessingShader();
4343 post_process_sprites.clear();
4344 setPostProcessingPresentFragmentShader(hdr_transfer_processing_enabled ? hdr_preview_shader_path(options, hdr_transfer_hlg).string() : std::string{});
4345 frame_sprite->setEffectsEnabled(effects_enabled);
4346
4347 const fs::path direct_model_shader = directModelFragmentShader();
4348 model_texture_prepass_active = model_3d_active && direct_model_shader.empty();
4349 setPostProcessingTextureConsumerEnabled(model_texture_prepass_active);
4350 if (model_initialized) {
4351 input_model.setColorAttachmentFormat(model_texture_prepass_active && !hdr_transfer_processing_enabled ? getSwapchainFormat() : getSceneColorFormat());
4352 const fs::path desired_model_shader = direct_model_shader.empty() ? model_fragment_shader_path(options) : direct_model_shader;
4353 if (desired_model_shader != model_effect_shader) {
4354 input_model.setShaders(this, model_vertex_shader_path(options).string(), desired_model_shader.string());
4355 model_effect_shader = desired_model_shader;
4356 }
4357 }
4358
4359 std::vector<fs::path> pipeline = activeShaderPipeline();
4360 if (!direct_model_shader.empty()) {
4361 const auto selected = std::find(pipeline.begin(), pipeline.end(), direct_model_shader);
4362 if (selected != pipeline.end()) {
4363 pipeline.erase(selected);
4364 }
4365 if (pipeline.empty()) {
4366 pipeline.emplace_back(passthrough_shader_path(options));
4367 }
4368 std::cout << "acmxvk: 3D texture effect: " << direct_model_shader.filename().string() << " [fragment, evaluated on model UVs]\n";
4369 } else if (model_3d_active && effects_enabled && !currentShader().empty()) {
4370 std::cout << "acmxvk: 3D texture prepass: fragment/compute "
4371 "chain output mapped onto model UVs\n";
4372 }
4374 pipeline.insert(pipeline.begin(), hdr_transfer_shader_path(options, hdr_transfer_hlg, false));
4375 pipeline.emplace_back(hdr_transfer_shader_path(options, hdr_transfer_hlg, true));
4376 }
4377 if (pipeline.empty()) {
4378 return;
4379 }
4380
4381 std::vector<PostProcessingEffect> effects;
4382 effects.reserve(pipeline.size());
4383 crossfade_post_process_index = std::numeric_limits<std::size_t>::max();
4384 for (std::size_t index = 0; index < pipeline.size(); ++index) {
4385 const fs::path &shader = pipeline[index];
4386 PostProcessingEffect effect{shader.string(), {1.0F, 1.0F, 1.0F, 0.0F}, false};
4389 effect.historySource = crossfade_previous_sprite;
4390 effect.params[0] = crossfade_alpha;
4391 } else if (options.human_background && shader == human_composite_shader_path(options)) {
4392 effect.historySource = human_overlay_sprite;
4393 } else if (historyCacheEnabled()) {
4394 effect.historySource = frame_sprite;
4395 }
4397 effect.spectrumBinCount = spectrumBinCount();
4398 }
4400 effect.spectrumHistoryLayerCount = static_cast<std::uint32_t>(options.audio_buffers);
4401 }
4402 effects.push_back(effect);
4403 }
4404 post_process_sprites = attachPostProcessingShaders(effects);
4405 for (mxvk::VK_Sprite *sprite : post_process_sprites) {
4406 sprite->enableExtendedUBO();
4407 sprite->setCustomUniforms(custom_uniform_values);
4409 sprite->enableSpectrumTexture(spectrumBinCount());
4410 }
4412 sprite->enableSpectrumHistoryTexture(spectrumBinCount(), static_cast<std::uint32_t>(options.audio_buffers));
4413 }
4414 }
4415
4416 std::cout << "acmxvk: Vulkan shader pipeline (" << pipeline.size() << " passes):\n";
4417 for (std::size_t index = 0; index < pipeline.size(); ++index) {
4418 const bool compute = index < post_process_effect_stages.size() && post_process_effect_stages[index] == mxvk::ShaderStage::Compute;
4419 std::cout << " " << (index + 1) << ": " << pipeline[index].filename().string() << " [" << (compute ? "compute" : "fragment") << "]\n";
4420 }
4421 }
4422
4424 if (!readInputFrame()) {
4425 return false;
4426 }
4430 } else if (source_kind == SourceKind::Camera) {
4432 }
4433 return true;
4434 }
4435
4436 [[nodiscard]] bool MainWindow::skipInputFrame() {
4438 return false;
4439 }
4440 bool skipped = false;
4441#ifdef MXVK_WITH_FFMPEG_CAPTURE
4442 if (using_ffmpeg_capture) {
4443 skipped = ffmpeg_capture.skip();
4444 } else
4445#endif
4446 {
4447 skipped = capture.grab();
4448 }
4449 if (skipped) {
4452 }
4453 return skipped;
4454 }
4455
4456 [[nodiscard]] bool MainWindow::handleCaptureEnd(bool discard) {
4458 return true;
4459 }
4460 if (!options.repeat) {
4461 setFrameReadbackEnabled(false);
4463 exit();
4464 return false;
4465 }
4466
4467#ifdef MXVK_WITH_FFMPEG_CAPTURE
4468 if (using_ffmpeg_capture && ffmpeg_capture.seek_start()) {
4470 const bool restarted = discard ? skipInputFrame() : readTrackedInputFrame();
4471 if (restarted) {
4472 if (!ffmpeg_seek_repeat_logged) {
4473 std::cout << "acmxvk: video repeat: in-place FFmpeg seek; " << (ffmpeg_capture.using_hardware_decode() ? "NVDEC decoder and CUDA device preserved\n" : "software decoder preserved\n");
4474 ffmpeg_seek_repeat_logged = true;
4475 }
4476 return true;
4477 }
4478 std::cerr << "acmxvk: in-place FFmpeg repeat did not produce a "
4479 "frame; reopening the input\n";
4480 }
4481#endif
4483 if (!openVideoCapture() || !(discard ? skipInputFrame() : readTrackedInputFrame())) {
4484 throw std::runtime_error("unable to restart video input: " + options.input_file);
4485 }
4486 return true;
4487 }
4488
4489 [[nodiscard]] bool MainWindow::readClockedVideoFrame(double clock_seconds) {
4490 const double rate = outputFrameRate();
4491 if (!std::isfinite(rate) || rate <= 0.0) {
4492 return readTrackedInputFrame();
4493 }
4494
4495 std::uint64_t target_frame = static_cast<std::uint64_t>(std::floor(std::max(clock_seconds, 0.0) * rate));
4496 if (target_frame < decoded_video_frame_count) {
4497 const double next_frame_time = static_cast<double>(decoded_video_frame_count) / rate;
4498 const double wait_seconds = next_frame_time - clock_seconds;
4499 if (wait_seconds > 0.0) {
4500 std::this_thread::sleep_for(std::chrono::duration<double>(wait_seconds));
4501 }
4502 double updated_clock = 0.0;
4503 if (mediaClockSeconds(updated_clock)) {
4504 target_frame = static_cast<std::uint64_t>(std::floor(std::max(updated_clock, 0.0) * rate));
4505 }
4506 }
4507 if (target_frame < decoded_video_frame_count) {
4508 return true;
4509 }
4510
4511 const std::uint64_t frames_to_advance = target_frame - decoded_video_frame_count + 1;
4512 for (std::uint64_t frame = 0; frame < frames_to_advance; ++frame) {
4513 const bool discard = frame + 1 < frames_to_advance;
4514 bool advanced = discard ? skipInputFrame() : readTrackedInputFrame();
4515 if (!advanced) {
4516 advanced = handleCaptureEnd(discard);
4517 }
4518 if (!advanced) {
4519 return false;
4520 }
4521 }
4522
4523 source_frame_received = true;
4524 recording_frame_due = true;
4528 std::cout << "acmxvk: media-clock synchronization active; "
4529 "late video frames will be skipped and encoded "
4530 "with timeline PTS\n";
4532 }
4533 return true;
4534 }
4535
4537#ifdef MXVK_WITH_FFMPEG_CAPTURE
4538 if (ffmpeg_capture.is_open()) {
4539 ffmpeg_capture.close();
4540 }
4541 using_ffmpeg_capture = false;
4542#endif
4543 if (capture.is_open()) {
4544 capture.close();
4545 }
4546 }
4547
4548 [[nodiscard]] bool MainWindow::openVideoCapture() {
4550 video_source_fps = 0.0;
4551#ifdef MXVK_WITH_FFMPEG_CAPTURE
4552 if (ffmpeg_capture.open(options.input_file, options.cuda_device)) {
4553 using_ffmpeg_capture = true;
4554 video_source_fps = ffmpeg_capture.fps();
4555 std::cout << "acmxvk: video capture: FFmpeg ";
4556 if (ffmpeg_capture.using_hardware_decode()) {
4557 std::cout << "with CUDA/NVDEC";
4558 if (ffmpeg_capture.hardware_decode_device() >= 0) {
4559 std::cout << " on device " << ffmpeg_capture.hardware_decode_device();
4560 }
4561 std::cout << '\n';
4562 } else {
4563 std::cout << "software decode\n";
4564 }
4565 return true;
4566 }
4567#endif
4568 const bool opened = capture.open(options.input_file);
4569 if (opened) {
4570 video_source_fps = capture.get(cv::CAP_PROP_FPS);
4571 std::cout << "acmxvk: video capture: OpenCV fallback\n";
4572 }
4573 if (!std::isfinite(video_source_fps) || video_source_fps <= 0.0) {
4574 video_source_fps = 30.0;
4575 }
4576 return opened;
4577 }
4578
4579 [[nodiscard]] bool MainWindow::readHostRgba(cv::Mat &rgba) {
4580#ifdef MXVK_WITH_FFMPEG_CAPTURE
4581 if (using_ffmpeg_capture) {
4582 int width = 0;
4583 int height = 0;
4584 int pitch = 0;
4586 if (!ffmpeg_capture.readRgba16(ffmpeg_rgba16, width, height, pitch, false) || ffmpeg_rgba16.empty() || width <= 0 || height <= 0 || pitch < width * 8) {
4587 return false;
4588 }
4589 rgba = cv::Mat(height, width, CV_16UC4, ffmpeg_rgba16.data(), static_cast<std::size_t>(pitch));
4590 return true;
4591 }
4592 if (!ffmpeg_capture.readRgba(ffmpeg_rgba, width, height, pitch, false) || ffmpeg_rgba.empty() || width <= 0 || height <= 0 || pitch < width * 4) {
4593 return false;
4594 }
4595 rgba = cv::Mat(height, width, CV_8UC4, ffmpeg_rgba.data(), static_cast<std::size_t>(pitch));
4596 return true;
4597 }
4598#endif
4599 return capture.readRgba(rgba, false);
4600 }
4601
4602 void MainWindow::initializeHistory(const cv::Mat &rgba) {
4604 return;
4605 }
4606 for (uint32_t layer = 0; layer < frame_sprite->getHistoryLayerCount(); ++layer) {
4607 updateHistoryFrame(rgba);
4608 }
4609 history_initialized = true;
4612 std::cout << "acmxvk: initialized " << frame_sprite->getHistoryLayerCount() << " Vulkan history-cache layers (delay " << options.cache_delay << ")\n";
4613 }
4614
4615 void MainWindow::updateHistoryFrame(const cv::Mat &rgba) {
4616#ifdef ACMXVK_WITH_CUDA
4617 if (gpu_filter_engine != nullptr && rgba.type() == CV_8UC4) {
4618 updateFilteredCudaHistoryFrame();
4619 return;
4620 }
4621#endif
4622 if (rgba.type() == CV_16UC4) {
4624 const cv::Mat linear_history = decode_hdr_transfer(rgba, hdr_transfer_hlg);
4625 frame_sprite->updateHistoryTextureRgba16(linear_history.ptr<std::uint16_t>(), linear_history.cols, linear_history.rows, static_cast<int>(linear_history.step));
4626 return;
4627 }
4628 frame_sprite->updateHistoryTextureRgba16(rgba.ptr<uint16_t>(), rgba.cols, rgba.rows, static_cast<int>(rgba.step));
4629 return;
4630 }
4631 frame_sprite->updateHistoryTexture(rgba.ptr(), rgba.cols, rgba.rows, static_cast<int>(rgba.step));
4632 }
4633
4636 return;
4637 }
4638
4639 const double rate = outputFrameRate();
4640 if (!std::isfinite(rate) || rate <= 0.0) {
4641 return;
4642 }
4643 const auto interval = std::chrono::duration_cast<std::chrono::steady_clock::duration>(std::chrono::duration<double>(static_cast<double>(options.cache_delay + 1) / rate));
4644 const auto now = std::chrono::steady_clock::now();
4646 camera_history_next_update = now + interval;
4648 return;
4649 }
4650 if (now < camera_history_next_update) {
4651 return;
4652 }
4653
4654 bool history_updated = false;
4655#if defined(ACMXVK_WITH_CUDA) && defined(ACMXVK_WITH_DEEP_DREAM) && defined(ACMXVK_WITH_MXVK_CUDA)
4656 if (options.gpu_filter_before_dream && deep_dream_model != nullptr && gpu_filter_engine != nullptr && !cuda_dream_rgba.empty()) {
4657 const cv::cuda::GpuMat &history_input = options.frame_rotation == FrameRotation::None ? cuda_dream_rgba : cuda_rotated_rgba;
4658 updateCudaHistoryFrame(history_input, gpu_filter_engine->stream());
4659 history_updated = true;
4660 }
4661#endif
4662#ifdef ACMXVK_WITH_CUDA
4663 if (!history_updated && gpu_filter_engine != nullptr) {
4664 updateFilteredCudaHistoryFrame();
4665 history_updated = true;
4666 }
4667#endif
4668 if (!history_updated && !latest_camera_history_rgba.empty()) {
4670 history_updated = true;
4671 }
4672 if (!history_updated) {
4673 return;
4674 }
4675
4676 camera_history_next_update += interval;
4677 if (camera_history_next_update <= now) {
4678 camera_history_next_update = now + interval;
4679 }
4680 }
4681
4682#ifdef ACMXVK_WITH_MXVK_CUDA
4683 void MainWindow::updateModelTextureCuda(const cv::cuda::GpuMat &rgba, cv::cuda::Stream &source_stream) {
4684 if (!model_initialized) {
4685 return;
4686 }
4687 if (input_model.updatePrimaryTextureCuda(rgba, source_stream)) {
4688 return;
4689 }
4690
4691 rgba.download(cuda_model_fallback_rgba, source_stream);
4692 source_stream.waitForCompletion();
4693 if (!cuda_model_fallback_logged) {
4694 std::cerr << "acmxvk: direct CUDA model-texture upload "
4695 "unavailable; using host staging\n";
4696 cuda_model_fallback_logged = true;
4697 }
4698 if (!input_model.updatePrimaryTexture(cuda_model_fallback_rgba.ptr(), cuda_model_fallback_rgba.cols, cuda_model_fallback_rgba.rows, static_cast<int>(cuda_model_fallback_rgba.step))) {
4699 throw std::runtime_error("MXVK could not update the 3D model texture");
4700 }
4701 }
4702
4703 void MainWindow::updateCudaHistoryFrame(const cv::cuda::GpuMat &rgba, cv::cuda::Stream &source_stream) {
4704 if (frame_sprite->updateHistoryTextureCuda(rgba, source_stream)) {
4705 return;
4706 }
4707
4708 rgba.download(cuda_history_fallback_rgba, source_stream);
4709 source_stream.waitForCompletion();
4710 if (!cuda_history_fallback_logged) {
4711 std::cerr << "acmxvk: direct CUDA history upload unavailable; "
4712 "using a host-staging fallback\n";
4713 cuda_history_fallback_logged = true;
4714 }
4715 frame_sprite->updateHistoryTexture(cuda_history_fallback_rgba.ptr(), cuda_history_fallback_rgba.cols, cuda_history_fallback_rgba.rows, static_cast<int>(cuda_history_fallback_rgba.step));
4716 }
4717
4718#ifdef ACMXVK_WITH_CUDA
4719 void MainWindow::updateFilteredCudaHistoryFrame() { updateCudaHistoryFrame(gpu_filter_engine->output(), gpu_filter_engine->stream()); }
4720#endif
4721
4722 void MainWindow::initializeCudaHistory(const cv::cuda::GpuMat &rgba, cv::cuda::Stream &source_stream, bool filtered) {
4723 if (!historyCacheEnabled() || history_initialized) {
4724 return;
4725 }
4726 for (uint32_t layer = 0; layer < frame_sprite->getHistoryLayerCount(); ++layer) {
4727 updateCudaHistoryFrame(rgba, source_stream);
4728 }
4729 history_initialized = true;
4730 history_delay_counter = 0;
4731 camera_history_clock_started = false;
4732 std::cout << "acmxvk: initialized " << frame_sprite->getHistoryLayerCount() << (filtered ? " filtered" : " NVDEC") << " Vulkan history-cache layers (delay " << options.cache_delay << ")\n";
4733 }
4734
4735#ifdef ACMXVK_WITH_CUDA
4736 void MainWindow::uploadInputFrame(const cv::cuda::GpuMat &rgba, cv::cuda::Stream &source_stream) {
4737 if (!gpu_filter_engine->process(rgba, source_stream)) {
4738 throw std::runtime_error("acidcam-gpu rejected the CUDA RGBA input frame");
4739 }
4740 if (!frame_sprite->updateTextureCuda(gpu_filter_engine->output(), gpu_filter_engine->stream())) {
4741 throw std::runtime_error("MXVK could not upload the CUDA-filtered frame");
4742 }
4743 updateModelTextureCuda(gpu_filter_engine->output(), gpu_filter_engine->stream());
4744 }
4745#endif
4746
4747 [[nodiscard]] const cv::cuda::GpuMat &MainWindow::rotateCudaFrame(const cv::cuda::GpuMat &rgba, cv::cuda::Stream &source_stream) {
4748 switch (options.frame_rotation) {
4750 return rgba;
4752 cv::cuda::transpose(rgba, cuda_rotation_transpose, source_stream);
4753 cv::cuda::flip(cuda_rotation_transpose, cuda_rotated_rgba, 1, source_stream);
4754 break;
4756 cv::cuda::flip(rgba, cuda_rotated_rgba, -1, source_stream);
4757 break;
4759 cv::cuda::transpose(rgba, cuda_rotation_transpose, source_stream);
4760 cv::cuda::flip(cuda_rotation_transpose, cuda_rotated_rgba, 0, source_stream);
4761 break;
4762 }
4763 return cuda_rotated_rgba;
4764 }
4765#endif
4766
4767 void MainWindow::uploadInputFrame(const cv::Mat &rgba) {
4768#ifdef ACMXVK_WITH_CUDA
4769 if (gpu_filter_engine != nullptr && rgba.type() == CV_8UC4) {
4770 if (!gpu_filter_engine->process(rgba)) {
4771 throw std::runtime_error("acidcam-gpu rejected the RGBA input frame");
4772 }
4773 if (!frame_sprite->updateTextureCuda(gpu_filter_engine->output(), gpu_filter_engine->stream())) {
4774 throw std::runtime_error("MXVK could not upload the CUDA-filtered frame");
4775 }
4776 updateModelTextureCuda(gpu_filter_engine->output(), gpu_filter_engine->stream());
4777 return;
4778 }
4779 if (gpu_filter_engine != nullptr && rgba.type() == CV_16UC4 && !hdr_cuda_filter_bypass_logged) {
4780 std::cout << "acmxvk: HDR increment 2: bypassing RGBA8 CUDA filters to "
4781 "preserve the 16-bit source texture\n";
4783 }
4784#endif
4785 if (rgba.type() == CV_16UC4) {
4786 frame_sprite->updateTextureRgba16(rgba.ptr<std::uint16_t>(), rgba.cols, rgba.rows, static_cast<int>(rgba.step));
4788 std::cout << "acmxvk: uploaded first RGBA16 HDR source frame "
4789 "to Vulkan\n";
4791 }
4792 } else {
4793 frame_sprite->updateTexture(rgba.ptr(), rgba.cols, rgba.rows, static_cast<int>(rgba.step));
4794 }
4795
4796 cv::Mat model_compatible;
4797 const cv::Mat *model_input = &rgba;
4798 if (model_initialized && rgba.type() == CV_16UC4) {
4799 model_compatible = rgba16ToRgba8(rgba);
4800 model_input = &model_compatible;
4801 }
4802 if (model_initialized && !input_model.updatePrimaryTexture(model_input->ptr(), model_input->cols, model_input->rows, static_cast<int>(model_input->step))) {
4803 throw std::runtime_error("MXVK could not update the 3D model texture");
4804 }
4805 }
4806
4808 cv::Mat bgr;
4811 if (!latest_camera_frame.takeLatest(bgr, wait_for_first)) {
4812 return false;
4813 }
4814
4815 cv::Mat rgba;
4816 cv::cvtColor(bgr, rgba, cv::COLOR_BGR2RGBA);
4817 applyDnnEffects(rgba);
4819 rotateFrame(rgba, options.frame_rotation);
4820 if (!human_overlay_rgba.empty()) {
4821 rotateFrame(human_overlay_rgba, options.frame_rotation);
4822 }
4823 uploadInputFrame(rgba);
4827
4828#ifdef ACMXVK_WITH_CUDA
4829 if (gpu_filter_engine != nullptr) {
4830 initializeCudaHistory(gpu_filter_engine->output(), gpu_filter_engine->stream(), true);
4831 return true;
4832 }
4833#endif
4834
4835 initializeHistory(rgba);
4836 return true;
4837 }
4838
4839#if defined(ACMXVK_WITH_MXVK_CUDA) && defined(ACMXVK_WITH_DEEP_DREAM)
4840 [[nodiscard]] bool MainWindow::readCudaDeepDreamFrame() {
4841 cv::cuda::Stream *capture_stream = nullptr;
4842#ifdef MXVK_WITH_FFMPEG_CAPTURE
4843 if (using_ffmpeg_capture) {
4844 if (!ffmpeg_capture.readGpuRgba(cuda_input_rgba, ffmpeg_cuda_stream, false)) {
4845 return false;
4846 }
4847 capture_stream = &ffmpeg_cuda_stream;
4848 } else
4849#endif
4850 {
4851 if (!capture.readGpuRgba(cuda_input_rgba, false)) {
4852 return false;
4853 }
4854 capture_stream = &capture.cudaStream();
4855 }
4856
4857 const cv::cuda::GpuMat *dream_input = &cuda_input_rgba;
4858 cv::cuda::Stream *dream_stream = capture_stream;
4859 bool filtered = false;
4860 const bool filter_before_dream = options.gpu_filter_before_dream;
4861#ifdef ACMXVK_WITH_CUDA
4862 if (filter_before_dream && gpu_filter_engine != nullptr) {
4863 if (!gpu_filter_engine->process(cuda_input_rgba, *capture_stream)) {
4864 throw std::runtime_error("acidcam-gpu rejected the pre-dream CUDA frame");
4865 }
4866 dream_input = &gpu_filter_engine->output();
4867 dream_stream = &gpu_filter_engine->stream();
4868 filtered = true;
4869 }
4870#endif
4871
4872 updateRandomDreamSettings();
4873 dream::GradientAscentResult dream_result;
4874 const cv::cuda::GpuMat *processed_input = dream_input;
4875 bool dream_processed = false;
4876 try {
4877 dream_result = deep_dream_model->apply_gradient_ascent_cuda(*dream_input, cuda_dream_rgba, *dream_stream, dream::GradientAscentOptions{options.dream_iterations, static_cast<float>(options.dream_strength), static_cast<float>(options.dream_feedback), static_cast<float>(options.dream_zoom), static_cast<float>(options.dream_rotation), options.dream_size, options.dream_channel, options.dream_octaves, static_cast<float>(options.dream_octave_scale), options.dream_jitter, options.dream_smoothing});
4878 dream_processed = std::isfinite(dream_result.mean_pixel_change);
4879 if (dream_processed) {
4880 processed_input = &cuda_dream_rgba;
4881 } else {
4882 handleDeepDreamRuntimeError("Deep Dream returned a non-finite CUDA frame");
4883 }
4884 } catch (const std::exception &error) {
4885 handleDeepDreamRuntimeError(error.what());
4886 }
4887
4888 const cv::cuda::GpuMat &render_input = rotateCudaFrame(*processed_input, *dream_stream);
4889 const cv::cuda::GpuMat *final_input = &render_input;
4890 cv::cuda::Stream *final_stream = dream_stream;
4891#ifdef ACMXVK_WITH_CUDA
4892 if (!filtered && gpu_filter_engine != nullptr) {
4893 if (!gpu_filter_engine->process(render_input, *dream_stream)) {
4894 throw std::runtime_error("acidcam-gpu rejected the post-dream CUDA frame");
4895 }
4896 final_input = &gpu_filter_engine->output();
4897 final_stream = &gpu_filter_engine->stream();
4898 filtered = true;
4899 }
4900#endif
4901 if (!frame_sprite->updateTextureCuda(*final_input, *final_stream)) {
4902 final_input->download(cuda_input_fallback_rgba, *final_stream);
4903 final_stream->waitForCompletion();
4904 if (!cuda_input_fallback_logged) {
4905 std::cerr << "acmxvk: direct Deep Dream/Vulkan upload "
4906 "unavailable; using host staging\n";
4907 cuda_input_fallback_logged = true;
4908 }
4909 frame_sprite->updateTexture(cuda_input_fallback_rgba.ptr(), cuda_input_fallback_rgba.cols, cuda_input_fallback_rgba.rows, static_cast<int>(cuda_input_fallback_rgba.step));
4910 }
4911 updateModelTextureCuda(*final_input, *final_stream);
4912
4913 if (dream_processed && !dream_processing_logged) {
4914 std::cout << "acmxvk: Deep Dream CUDA working frame: " << dream_result.processed_width << 'x' << dream_result.processed_height << " -> " << render_input.cols << 'x' << render_input.rows << " Vulkan texture (" << dream_result.processed_octaves << " octave(s))\n";
4915 dream_processing_logged = true;
4916 }
4917 if (!cuda_input_path_logged) {
4918 std::cout << "acmxvk: CUDA interop path active: capture/NVDEC -> ";
4919 if (filter_before_dream && filtered) {
4920 std::cout << "acidcam-gpu -> ";
4921 }
4922 if (dream_processed) {
4923 std::cout << "LibTorch Deep Dream -> ";
4924 }
4925 if (options.frame_rotation != FrameRotation::None) {
4926 std::cout << "CUDA rotation -> ";
4927 }
4928 if (!filter_before_dream && filtered) {
4929 std::cout << "acidcam-gpu -> ";
4930 }
4931 std::cout << "Vulkan texture";
4932 if (cuda_input_fallback_logged) {
4933 std::cout << " (host-staging upload fallback)";
4934 }
4935 std::cout << '\n';
4936 cuda_input_path_logged = true;
4937 }
4938
4939 const bool history_was_initialized = history_initialized;
4940 initializeCudaHistory(*final_input, *final_stream, filtered);
4941 if (source_kind != SourceKind::Camera && history_was_initialized && ++history_delay_counter > options.cache_delay) {
4942 updateCudaHistoryFrame(*final_input, *final_stream);
4943 history_delay_counter = 0;
4944 }
4945 if (source_kind == SourceKind::Camera) {
4946 camera_history_clock_started = false;
4947 }
4948 return true;
4949 }
4950#endif
4951
4952 [[nodiscard]] bool MainWindow::readInputFrame() {
4953 if (source_kind == SourceKind::Camera && options.maximize_fps) {
4954 return readLatestCameraFrame();
4955 }
4956#if defined(ACMXVK_WITH_MXVK_CUDA) && defined(ACMXVK_WITH_DEEP_DREAM)
4958#ifdef ACMXVK_WITH_DNN
4959 && edge_detector == nullptr && human_segmenter == nullptr && generic_onnx_processor == nullptr
4960#endif
4961#ifdef ACMXVK_WITH_STABLE_DIFFUSION
4962 && (stable_diffusion_server == nullptr || options.stable_diffusion_after_shaders)
4963#endif
4964 ) {
4965 return readCudaDeepDreamFrame();
4966 }
4967#endif
4968#ifdef ACMXVK_WITH_CUDA
4969 if (gpu_filter_engine != nullptr && !hostPreprocessingEnabled() && !hdr_input_precision_enabled) {
4970 cv::cuda::Stream *capture_stream = nullptr;
4971#ifdef MXVK_WITH_FFMPEG_CAPTURE
4972 if (using_ffmpeg_capture) {
4973 if (!ffmpeg_capture.readGpuRgba(cuda_input_rgba, ffmpeg_cuda_stream, false)) {
4974 return false;
4975 }
4976 capture_stream = &ffmpeg_cuda_stream;
4977 } else
4978#endif
4979 {
4980 if (!capture.readGpuRgba(cuda_input_rgba, false)) {
4981 return false;
4982 }
4983 capture_stream = &capture.cudaStream();
4984 }
4985 const cv::cuda::GpuMat &filter_input = rotateCudaFrame(cuda_input_rgba, *capture_stream);
4986 uploadInputFrame(filter_input, *capture_stream);
4987 if (!cuda_input_path_logged) {
4988#ifdef MXVK_WITH_FFMPEG_CAPTURE
4989 if (using_ffmpeg_capture) {
4990 std::cout << "acmxvk: CUDA input path active: FFmpeg " << (ffmpeg_capture.using_hardware_decode() ? "NVDEC -> CUDA RGBA -> " : "software decode -> CUDA upload -> ");
4991 } else
4992#endif
4993 {
4994 std::cout << "acmxvk: CUDA input path active: MXVK capture -> ";
4995 }
4996 if (options.frame_rotation != FrameRotation::None) {
4997 std::cout << "CUDA rotation -> ";
4998 }
4999 std::cout << "acidcam-gpu temporal buffer -> Vulkan texture\n";
5000 cuda_input_path_logged = true;
5001 }
5002 const bool history_was_initialized = history_initialized;
5003 initializeCudaHistory(gpu_filter_engine->output(), gpu_filter_engine->stream(), true);
5004 if (source_kind != SourceKind::Camera && history_was_initialized && ++history_delay_counter > options.cache_delay) {
5005 updateFilteredCudaHistoryFrame();
5007 }
5008 return true;
5009 }
5010#endif
5011#ifdef ACMXVK_WITH_MXVK_CUDA
5012#if defined(MXVK_WITH_FFMPEG_CAPTURE)
5013 if (using_ffmpeg_capture && ffmpeg_capture.using_hardware_decode() && !hostPreprocessingEnabled() && !hdr_input_precision_enabled) {
5014 if (!ffmpeg_capture.readGpuRgba(cuda_input_rgba, ffmpeg_cuda_stream, false)) {
5015 return false;
5016 }
5017 const cv::cuda::GpuMat &render_input = rotateCudaFrame(cuda_input_rgba, ffmpeg_cuda_stream);
5018 if (!frame_sprite->updateTextureCuda(render_input, ffmpeg_cuda_stream)) {
5019 render_input.download(cuda_input_fallback_rgba, ffmpeg_cuda_stream);
5020 ffmpeg_cuda_stream.waitForCompletion();
5021 if (!cuda_input_fallback_logged) {
5022 std::cerr << "acmxvk: direct NVDEC/Vulkan upload unavailable; "
5023 "using host staging\n";
5024 cuda_input_fallback_logged = true;
5025 }
5026 frame_sprite->updateTexture(cuda_input_fallback_rgba.ptr(), cuda_input_fallback_rgba.cols, cuda_input_fallback_rgba.rows, static_cast<int>(cuda_input_fallback_rgba.step));
5027 }
5028 updateModelTextureCuda(render_input, ffmpeg_cuda_stream);
5029 if (!cuda_input_path_logged) {
5030 std::cout << "acmxvk: CUDA input path active: FFmpeg "
5031 "NVDEC -> CUDA RGBA -> ";
5032 if (options.frame_rotation != FrameRotation::None) {
5033 std::cout << "CUDA rotation -> ";
5034 }
5035 std::cout << "Vulkan texture";
5036 if (cuda_input_fallback_logged) {
5037 std::cout << " (host-staging fallback)";
5038 }
5039 std::cout << '\n';
5040 cuda_input_path_logged = true;
5041 }
5042 const bool history_was_initialized = history_initialized;
5043 initializeCudaHistory(render_input, ffmpeg_cuda_stream, false);
5044 if (history_was_initialized && ++history_delay_counter > options.cache_delay) {
5045 updateCudaHistoryFrame(render_input, ffmpeg_cuda_stream);
5047 }
5048 return true;
5049 }
5050#endif
5051#endif
5052
5054 if (!requires_host_frame
5055#ifdef MXVK_WITH_FFMPEG_CAPTURE
5056 && !using_ffmpeg_capture
5057#endif
5058 ) {
5059 return capture.readToSprite(*frame_sprite, false);
5060 }
5061
5062 cv::Mat rgba;
5063 if (!readHostRgba(rgba)) {
5064 return false;
5065 }
5066 applyDnnEffects(rgba);
5069 rotateFrame(rgba, options.frame_rotation);
5070 if (!human_overlay_rgba.empty()) {
5071 rotateFrame(human_overlay_rgba, options.frame_rotation);
5072 }
5073 uploadInputFrame(rgba);
5077 }
5078 const bool history_was_initialized = history_initialized;
5079 initializeHistory(rgba);
5080 if (source_kind != SourceKind::Camera && history_was_initialized && ++history_delay_counter > options.cache_delay) {
5081 updateHistoryFrame(rgba);
5083 }
5084 return true;
5085 }
5086
5087 void MainWindow::updateShaderUniforms(int width, int height) {
5088 const auto now = std::chrono::steady_clock::now();
5089 updateCrossfade(now);
5090 const float wall_delta = std::chrono::duration<float>(now - previous_frame).count();
5091 previous_frame = now;
5092 ++frame_count;
5093
5094 double video_timeline = 0.0;
5095 const bool video_timeline_available = currentVideoTimeline(video_timeline);
5096 float delta = wall_delta;
5097 if (video_timeline_available) {
5099 std::cout << "acmxvk: shader clock: decoded video timeline; "
5100 "effects are independent of processing speed\n";
5102 }
5105 shader_time = 0.0;
5106 frame_count = 1;
5107 }
5108 delta = 0.0F;
5110 } else {
5111 delta = static_cast<float>(video_timeline - previous_video_shader_timeline);
5112 }
5113 previous_video_shader_timeline = video_timeline;
5114 } else if (options.normalized_time) {
5115 delta = static_cast<float>(1.0 / outputFrameRate());
5116 }
5117 const float frame_rate = video_timeline_available ? static_cast<float>(video_source_fps) : (delta > 0.0F ? 1.0F / delta : 0.0F);
5118 float raw_audio_amplitude = 0.0F;
5119 float audio_sensitivity = 1.0F;
5120 float audio_amplitude = 0.0F;
5121 float audio_frequency = 0.0F;
5122 float audio_peak = 0.0F;
5123 float audio_rms = 0.0F;
5124 float audio_smooth = 0.0F;
5125 float audio_low = 0.0F;
5126 float audio_mid = 0.0F;
5127 float audio_high = 0.0F;
5128 float audio_sample_rate = 44100.0F;
5129#ifdef AUDIO_ENABLED
5130 std::vector<float> spectrum_values;
5131 if (file_audio_source != nullptr && audio_engine != nullptr && media_timeline_started && (file_audio_source->has_output_clock() || source_frame_received)) {
5132 double source_audio_time = 0.0;
5133 const bool offline_source_audio = offlineSourceAudioEnabled();
5134 const bool source_audio_timeline = options.use_source_audio && ((offline_source_audio && currentVideoTimeline(source_audio_time)) || (!offline_source_audio && !file_audio_source->has_output_clock() && mediaClockSeconds(source_audio_time)));
5135 if (source_audio_timeline) {
5136 file_audio_source->process_at_time(source_audio_time, outputFrameRate(), *audio_engine);
5137 } else {
5139 }
5140 if (options.audio_trunc && !file_audio_source->is_active()) {
5141 std::cout << "acmxvk: audio source finished, stopping "
5142 "(--audio-trunc)\n";
5143 exit();
5144 }
5145 }
5146 if (audioSourceOpen()) {
5147 const audio::AudioMetrics metrics = audio_engine->metrics();
5148 const float warmup = offlineSourceAudioEnabled() && video_timeline_available ? (options.audio_warm_rate <= 0.0 ? 1.0F : std::min(static_cast<float>(video_timeline * options.audio_warm_rate), 1.0F)) : updateAudioWarmup(now);
5149 raw_audio_amplitude = metrics.amplitude;
5150 audio_sensitivity = audio_engine->sensitivity();
5151 const float delta_scale = audio_delta_time ? delta : 1.0F;
5152 const float sense = audio_sensitivity * 4.0F * warmup;
5153 audio_amplitude = raw_audio_amplitude * audio_sensitivity * static_cast<float>(options.time_speed) * delta_scale * warmup;
5154 audio_frequency = metrics.frequency;
5155 audio_peak = std::sqrt(std::max(metrics.peak, 0.0F)) * sense;
5156 audio_rms = std::sqrt(std::max(metrics.rms, 0.0F)) * sense;
5157 audio_smooth = std::sqrt(std::max(metrics.smooth, 0.0F)) * sense;
5158 audio_low = std::sqrt(std::max(metrics.low, 0.0F)) * sense;
5159 audio_mid = std::sqrt(std::max(metrics.mid, 0.0F)) * sense;
5160 audio_high = std::sqrt(std::max(metrics.high, 0.0F)) * sense;
5161 audio_sample_rate = static_cast<float>(audio_engine->sample_rate());
5162 spectrum_values = audio_engine->spectrum();
5163 const float spectrum_scale = warmup * (spectrum_scale_by_sensitivity ? audio_sensitivity : 1.0F);
5164 for (float &value : spectrum_values) {
5165 value *= spectrum_scale;
5166 }
5167 }
5168#endif
5169 if (audio_time_active) {
5170 const float delta_scale = audio_delta_time ? delta : 1.0F;
5171 shader_time += static_cast<double>(raw_audio_amplitude) * static_cast<double>(audio_sensitivity) * options.time_speed * static_cast<double>(delta_scale);
5172 } else if (shader_time_active) {
5173 shader_time += static_cast<double>(delta) * options.time_speed;
5174 }
5175 if (!std::isfinite(shader_time)) {
5176 shader_time = 0.0;
5177 }
5178 model_wave_audio_step = audio_amplitude * raw_audio_amplitude;
5179 if (video_timeline_available) {
5180 const std::uint64_t source_frame = video_source_frame_count - 1U;
5181 if (source_frame <= 58U) {
5182 legacy_alpha = 0.2F + 0.1F * static_cast<float>(source_frame);
5183 } else {
5184 const std::uint64_t phase = (source_frame - 59U) % 100U;
5185 legacy_alpha = phase < 50U ? 5.9F - 0.1F * static_cast<float>(phase) : 1.1F + 0.1F * static_cast<float>(phase - 50U);
5186 }
5187 } else if (legacy_alpha_increasing) {
5188 legacy_alpha += 0.1F;
5189 if (legacy_alpha >= 6.0F) {
5190 legacy_alpha = 6.0F;
5192 }
5193 } else {
5194 legacy_alpha -= 0.1F;
5195 if (legacy_alpha <= 1.0F) {
5196 legacy_alpha = 1.0F;
5198 }
5199 }
5200 const float elapsed = static_cast<float>(shader_time);
5201 const float compatibility_time = video_timeline_available ? static_cast<float>(video_timeline) : std::chrono::duration<float>(now - compatibility_clock_start).count();
5202 const float shader_frame = video_timeline_available ? static_cast<float>(video_source_frame_count - 1U) : static_cast<float>(frame_count);
5203 frame_sprite->setShaderParams(1.0F, 1.0F, 1.0F, elapsed);
5204 frame_sprite->setMouseState(mouse_x, mouse_y, mouse_pressed ? 1.0F : 0.0F);
5205 frame_sprite->setUniform0(legacy_alpha, compatibility_time, static_cast<float>(width), static_cast<float>(height));
5206 frame_sprite->setUniform1(delta, audio_amplitude, audio_frequency, frame_rate);
5207 frame_sprite->setUniform2(shader_frame, elapsed, audio_sample_rate, audio_peak);
5208 frame_sprite->setUniform3(static_cast<float>(frame_sprite->getHistoryHead()), static_cast<float>(frame_sprite->getHistoryLayerCount()), audio_rms, audio_smooth);
5209 frame_sprite->setAudioBands(audio_low, audio_mid, audio_high);
5210
5212 model_fragment_uniforms.mouse = glm::vec4(mouse_x, mouse_y, mouse_pressed ? 1.0F : 0.0F, 0.0F);
5213 model_fragment_uniforms.u0 = glm::vec4(legacy_alpha, compatibility_time, static_cast<float>(width), static_cast<float>(height));
5214 model_fragment_uniforms.u1 = glm::vec4(delta, audio_amplitude, audio_frequency, frame_rate);
5215 model_fragment_uniforms.u2 = glm::vec4(shader_frame, elapsed, audio_sample_rate, audio_peak);
5216 model_fragment_uniforms.u3 = glm::vec4(static_cast<float>(frame_sprite->getHistoryHead()), static_cast<float>(frame_sprite->getHistoryLayerCount()), audio_rms, audio_smooth);
5217 for (std::size_t index = 0; index < custom_uniform_values.size() && index < 64U; ++index) {
5218 model_fragment_uniforms.custom_uniforms[index / 4U][index % 4U] = custom_uniform_values[index];
5219 }
5220 model_fragment_uniforms.audio_bands = glm::vec4(audio_low, audio_mid, audio_high, 0.0F);
5221
5222 for (std::size_t index = 0; index < post_process_sprites.size(); ++index) {
5223 mxvk::VK_Sprite *sprite = post_process_sprites[index];
5225 setPostProcessingShaderParams(index, crossfade_alpha, 0.0F, 0.0F, 0.0F);
5226 } else {
5227 setPostProcessingShaderParams(index, 1.0F, 1.0F, 1.0F, elapsed);
5228 }
5229 sprite->setMouseState(mouse_x, mouse_y, mouse_pressed ? 1.0F : 0.0F);
5230 sprite->setUniform0(legacy_alpha, compatibility_time, static_cast<float>(width), static_cast<float>(height));
5231 sprite->setUniform1(delta, audio_amplitude, audio_frequency, frame_rate);
5232 sprite->setUniform2(shader_frame, elapsed, audio_sample_rate, audio_peak);
5233 sprite->setUniform3(static_cast<float>(frame_sprite->getHistoryHead()), static_cast<float>(frame_sprite->getHistoryLayerCount()), audio_rms, audio_smooth);
5234 sprite->setAudioBands(audio_low, audio_mid, audio_high);
5235 }
5236#ifdef AUDIO_ENABLED
5237 if (!spectrum_values.empty()) {
5238 frame_sprite->updateSpectrumTexture(spectrum_values.data(), static_cast<std::uint32_t>(spectrum_values.size()));
5239 if (options.audio_buffers > 0) {
5240 frame_sprite->updateSpectrumHistoryTexture(spectrum_values.data(), static_cast<std::uint32_t>(spectrum_values.size()));
5241 }
5242 for (mxvk::VK_Sprite *sprite : post_process_sprites) {
5243 sprite->updateSpectrumTexture(spectrum_values.data(), static_cast<std::uint32_t>(spectrum_values.size()));
5244 if (options.audio_buffers > 0) {
5245 sprite->updateSpectrumHistoryTexture(spectrum_values.data(), static_cast<std::uint32_t>(spectrum_values.size()));
5246 }
5247 }
5248 }
5249#endif
5250 }
5251
5252} // namespace acmxvk
void transfer_audio(std::string_view, std::string_view)
Copy the audio track from one media file to another via FFmpeg.
std::chrono::steady_clock::duration source_playback_paused_duration
std::unordered_map< std::string, fs::path > shader_reload_overrides
std::unique_ptr< midi::MidiInput > midi_input
std::unique_ptr< audio::FileAudioSource > file_audio_source
InterfaceClient interface_client
void applyStableDiffusionEffect(cv::Mat &rgba)
void requestSnapshot(SnapshotFormat format)
std::vector< std::uint16_t > gap_fill_previous_rgba16
mxvk::ModelFragmentUniforms model_fragment_uniforms
std::uint64_t previous_autopilot_video_frame
void updateCrossfade(const std::chrono::steady_clock::time_point now)
std::chrono::steady_clock::time_point hud_session_start
fs::path resolvedShaderPath(const fs::path &shader) const
std::uint64_t hud_fps_frame_count
void queueRuntimeHud(int &y, int line_height)
std::vector< mxvk::VK_Sprite * > post_process_sprites
std::uint64_t output_frame_count
void event(SDL_Event &event) override
void setSourcePlaybackClockPaused(bool paused)
std::chrono::steady_clock::time_point source_playback_clock_start
std::chrono::steady_clock::time_point source_playback_pause_start
mxvk::VK_Sprite * crossfade_previous_sprite
void adjustAudioSensitivity(float amount)
std::chrono::steady_clock::time_point camera_fps_last_tick
void cycleCrossfade(int direction)
void adjustModelScale(float amount)
void dispatchMidiAction(int action)
const std::vector< fs::path > * activePasses() const
bool mediaClockSeconds(double &seconds) const
std::vector< float > custom_uniform_values
void onSwapchainRecreated() override
std::chrono::steady_clock::time_point audio_warmup_last_tick
std::string activePassDescription() const
double hudVideoPositionSeconds() const
std::chrono::steady_clock::time_point window_title_last_update
std::deque< ReadbackRequest > readback_requests
MainWindow(Options options)
std::uint64_t generated_frame_count
void onRecordPostProcessingTexture(VkCommandBuffer command_buffer, std::uint32_t image_index, VkImageView texture_view, VkExtent2D texture_extent) override
void apply_interface_gpu_filter_state(const InterfaceGpuFilterState &requested, bool announce)
void apply_interface_audio_file_state(const InterfaceAudioFileState &requested)
std::vector< MidiKnobState > midi_knob_states
void apply_interface_shader_reload(const InterfaceReloadState &requested)
std::uint64_t gap_fill_duplicate_count
void updateWindowTitle(bool force=false)
bool continuousReadbackEnabled() const
void applyDnnEffects(cv::Mat &rgba)
std::array< int, 4 > midi_slider_uniform_indices
std::string_view activeShaderRole() const
float updateAudioWarmup(std::chrono::steady_clock::time_point now)
fs::path directModelFragmentShader() const
std::uint64_t recording_frame_pts
mxvk::VK_Sprite * frame_sprite
void handleFrameReadback(std::vector< std::uint8_t > &rgba, const std::vector< std::uint16_t > *rgba16, uint32_t width, uint32_t height)
std::vector< std::uint8_t > gap_fill_previous_rgba
std::chrono::steady_clock::time_point interface_next_connect_attempt
std::uint64_t observed_midi_drops
void onRecordCustomRendering(VkCommandBuffer command_buffer, std::uint32_t image_index) override
void onFrameReadbackRgba16(std::vector< std::uint16_t > &rgba, uint32_t width, uint32_t height) override
std::uint64_t gap_fill_next_pts
bool isMidiModelAction(int action) const
bool isMidiMappingSupported(const midi::MidiMapping &mapping) const
void selectGpuFilter(int direction)
void apply_interface_deep_dream_state(const InterfaceDeepDreamState &requested, bool announce)
bool spectrumHistoryEnabledForShaders() const
std::uint64_t next_clock_output_frame
std::chrono::steady_clock::time_point crossfade_start_time
static std::string formatHudTime(double seconds_value)
bool applyMidiCc(const midi::MidiMessage &message)
void apply_interface_overlay_state(const InterfaceOverlayState &requested, bool announce)
std::chrono::steady_clock::time_point previous_frame
void apply_interface_playback_state(const InterfacePlaybackState &requested, bool announce)
std::chrono::steady_clock::time_point hud_fps_last_tick
bool offlineSourceAudioEnabled() const
static bool usesMidiDeltaDirection(const midi::MidiMapping &mapping)
std::string hudVideoTimeString() const
bool readHostRgba(cv::Mat &rgba)
void toggleAutopilot(bool sequential)
std::uint32_t interface_last_reload_sequence
void recordModel(VkCommandBuffer command_buffer, std::uint32_t image_index, VkImageView texture_view)
void logSelectedPlaylistNode(std::string_view action) const
std::unique_ptr< audio::AudioEngine > audio_engine
std::vector< MidiCcMapping > midi_cc_mappings
mxvk::VK_Sprite * human_overlay_sprite
void apply_interface_uniform_values(const std::vector< InterfaceUniformValue > &uniform_values)
std::vector< fs::path > activeShaderPipeline() const
std::chrono::steady_clock::time_point next_render_tick
void stepShaderTime(double amount)
std::uint64_t previous_model_video_frame
void onFrameReadbackScheduled() override
bool hostPreprocessingEnabled() const
double hudWallElapsedSeconds() const
std::string activePlaylistDescription() const
void handleDeepDreamRuntimeError(std::string_view message)
SnapshotFormat pending_snapshot_format
std::string hudElapsedTimeString() const
std::pair< int, int > source_dimensions()
void apply_interface_multipass_state(const InterfaceMultipassState &requested)
std::uint64_t camera_fps_frame_count
static std::string captureFourccName(double value)
void initializeHistory(const cv::Mat &rgba)
std::uint32_t spectrumBinCount() const
void applyDeepDreamEffect(cv::Mat &rgba)
std::chrono::steady_clock::time_point camera_history_next_update
bool handleCaptureEnd(bool discard=false)
std::uint32_t interface_last_audio_file_sequence
void adjustTimeSpeed(double amount)
void uploadInputFrame(const cv::Mat &rgba)
void cancelStableDiffusionInitialization() noexcept
SDL_Keycode midiActionKey(int action) const
bool readClockedVideoFrame(double clock_seconds)
bool currentVideoTimeline(double &timeline, std::uint64_t *frame_index=nullptr) const
void updateShaderUniforms(int width, int height)
LatestCameraFrame latest_camera_frame
std::chrono::steady_clock::time_point headless_progress_last_emit
std::vector< fs::path > configured_passes
bool applyMidiMap(const midi::MidiMessage &message)
bool spectrumTextureEnabledForShaders() const
std::vector< midi::MidiMapping > midi_action_mappings
void apply_interface_shader_selection(const std::string &requested_name)
bool isMidiSliderMapping(const midi::MidiMapping &mapping) const
void recordShaderResources(const mxvk::ShaderModuleInfo &module_info, std::string_view source)
std::vector< PlaylistNode > playlist
static std::string clipOverlayText(std::string text)
static constexpr std::uint32_t COMPATIBILITY_SPECTRUM_BIN_COUNT
bool setMidiUniform(std::size_t uniform_index, int value, std::string_view label)
std::uint64_t autopilotFrameAdvance()
mxvk::VKAbstractModel input_model
void emitHeadlessProgress(bool complete)
std::chrono::steady_clock::time_point compatibility_clock_start
std::vector< fs::path > shaders
void onFrameReadback(std::vector< std::uint8_t > &rgba, uint32_t width, uint32_t height) override
std::vector< ShaderManifest::CustomUniform > custom_uniforms
std::uint32_t interface_last_sequence
std::string_view midiActionName(int action) const
void updateHistoryFrame(const cv::Mat &rgba)
std::size_t crossfade_post_process_index
std::uint64_t video_source_frame_count
std::chrono::steady_clock::time_point model_last_render_time
std::string currentShader() const
SnapshotWriter snapshot_writer
void dispatchMidiModelAction(int action)
void selectShader(int direction)
std::uint64_t decoded_video_frame_count
std::uint64_t random_dream_period
void selectPlaylistNode(int direction)
static std::string_view formatName(SnapshotFormat format) noexcept
static void savePng(const fs::path &path, std::uint8_t *rgba, int width, int height, int png_level)
static constexpr std::uint32_t spectrum_bin_count()
static bool mux_recording_into_video(std::vector< float > samples, unsigned int sample_rate, const std::string &video_path, double video_duration)
std::size_t selected_channels() const
static Model load(std::string_view filename, int cuda_device, std::string_view layer={}, bool use_half=false)
cv::Mat decode_hdr_transfer(const cv::Mat &rgba, bool hlg)
std::string format_bitrate(std::uint64_t bytes_written, double duration_seconds)
volatile std::sig_atomic_t HEADLESS_SHUTDOWN_REQUESTED
std::vector< std::uint8_t > tone_map_hdr_rgba16(const std::vector< std::uint16_t > &rgba, bool hlg)
bool write_wav_file(const AudioRecording &recording, const std::string &filename)
cv::Mat hardenedAlphaMask(const cv::Mat &image, const cv::Mat &mask, float black_point, float white_point)
Definition edge_dnn.cpp:636
cv::Mat isolateBody(const cv::Mat &image, const cv::Mat &mask, float black_point, float white_point)
Definition edge_dnn.cpp:645
void validate_file_size(const std::filesystem::path &path, std::string_view context, std::uintmax_t maximum_bytes)
void validate_spirv_file(const std::filesystem::path &path, std::string_view context)
std::string truncate_utf8(std::string_view value, std::size_t maximum_bytes, std::string_view suffix)
void validate_string(std::string_view value, StringKind kind, std::string_view context, bool allow_empty)
std::vector< MidiMapping > load_mapping_file(const std::string &filename)
Definition midi.cpp:53
std::vector< PlaylistNode > load_playlist(const fs::path &playlist_path, const std::vector< fs::path > &available_shaders, const fs::path &library_directory, std::ostream &warning_output)
fs::path resolveShaderManifestEntry(const fs::path &directory, std::string entry)
cv::Mat loadRgbaImage(const std::string &filename)
bool rotationSwapsDimensions(FrameRotation rotation)
fs::path default_model_path(const Options &options)
fs::path snapshot_path(const fs::path &directory, std::uint32_t width, std::uint32_t height, std::uint64_t &counter, SnapshotFormat format, std::chrono::system_clock::time_point timestamp)
std::size_t playlist_shader_count(const std::vector< PlaylistNode > &playlist) noexcept
fs::path echo_cache_shader_path(const Options &options)
double probeVideoDuration(const std::string &filename)
std::string trim(std::string text)
Definition options.cpp:1454
fs::path human_composite_shader_path(const Options &options)
ShaderManifest loadShaderManifest(const fs::path &directory)
fs::path model_fragment_shader_path(const Options &options)
void printVideoHdrInfo(const VideoHdrInfo &info, std::ostream &output)
fs::path model_vertex_shader_path(const Options &options)
void request_headless_shutdown(int signal_number) noexcept
int parseInteger(std::string_view text, std::string_view option)
Definition options.cpp:124
bool dimensions_supported(int width, int height)
Definition options.cpp:50
void rotateFrame(cv::Mat &frame, FrameRotation rotation)
fs::path passthrough_shader_path(const Options &options)
fs::path frame_path(const fs::path &directory, std::uint64_t index)
VideoHdrInfo probeVideoHdrInfo(const std::string &filename)
fs::path hdr_preview_shader_path(const Options &options, bool hlg)
fs::path find_shader_path(const std::vector< fs::path > &available_shaders, const fs::path &library_directory, std::string name)
fs::path crossfade_shader_path(const Options &options, std::size_t shader_index)
fs::path stable_diffusion_upscale_shader_path(const Options &options)
fs::path sprite_vertex_shader_path(const Options &options)
fs::path hdr_transfer_shader_path(const Options &options, bool hlg, bool encode)
double parseNumber(std::string_view text, std::string_view option)
Definition options.cpp:139
void create_output_directory(const fs::path &directory)
bool isValidCustomUniformName(const std::string &name)
constexpr std::array< std::string_view, 35 > CROSSFADE_NAMES
Definition options.hpp:15
fs::path overlay_font_path(const Options &options)
fs::path flip_shader_path(const Options &options)
fs::path find_resource(const Options &options, const fs::path &relative_path)
std::vector< std::string > shader_names
std::array< std::uint8_t, 3 > watermark_color
InterfaceOverlayState overlay
std::vector< InterfaceUniformValue > uniform_values
InterfaceAudioFileState audio_file
InterfaceMultipassState multipass
InterfaceGpuFilterState gpu_filters
InterfaceReloadState reload
InterfacePlaybackState playback
InterfaceDeepDreamState deep_dream
bool enable_audio_time
Definition options.hpp:105
int stable_diffusion_upscale_working_width
Definition options.hpp:56
int audio_output_device
Definition options.hpp:43
std::string edge_model
Definition options.hpp:193
bool stable_diffusion_after_shaders
Definition options.hpp:146
bool midi_device_specified
Definition options.hpp:117
bool stable_diffusion_quiet
Definition options.hpp:149
double audio_recording_gain
Definition options.hpp:69
std::string stable_diffusion_model
Definition options.hpp:198
double dream_octave_scale
Definition options.hpp:76
std::string dream_layer
Definition options.hpp:197
std::string stable_diffusion_server
Definition options.hpp:202
bool use_source_audio
Definition options.hpp:84
double random_dream_interval
Definition options.hpp:77
std::string stable_diffusion_scheduler
Definition options.hpp:204
bool gpu_filter_before_dream
Definition options.hpp:144
std::string dream_model
Definition options.hpp:196
int stable_diffusion_server_port
Definition options.hpp:60
double audio_pass_through_gain
Definition options.hpp:68
std::vector< std::string > stable_diffusion_server_arguments
Definition options.hpp:170
double dream_rotation
Definition options.hpp:75
std::vector< StableDiffusionLora > stable_diffusion_loras
Definition options.hpp:169
std::string fragment_shader
Definition options.hpp:174
bool random_dream_specified
Definition options.hpp:141
std::string audio_file
Definition options.hpp:190
bool human_background
Definition options.hpp:150
std::string output_file
Definition options.hpp:182
std::string midi_map_file
Definition options.hpp:192
double stable_diffusion_strength
Definition options.hpp:78
int stable_diffusion_height
Definition options.hpp:55
std::vector< int > gpu_filter_indices
Definition options.hpp:168
std::string watermark_text
Definition options.hpp:207
int stable_diffusion_width
Definition options.hpp:54
double dream_feedback
Definition options.hpp:73
std::vector< std::string > midi_cc_mappings
Definition options.hpp:167
std::string stable_diffusion_upscale_model
Definition options.hpp:199
double dream_strength
Definition options.hpp:72
int audio_input_device
Definition options.hpp:42
bool stable_diffusion_upscale
Definition options.hpp:147
double audio_warm_rate
Definition options.hpp:67
int stable_diffusion_upscale_working_height
Definition options.hpp:57
double stable_diffusion_cfg_scale
Definition options.hpp:79
std::string shader_directory
Definition options.hpp:173
std::string onnx_configuration
Definition options.hpp:195
std::string record_audio_file
Definition options.hpp:191
std::string stable_diffusion_sampler
Definition options.hpp:203
std::string human_model
Definition options.hpp:194
std::string stable_diffusion_negative_prompt
Definition options.hpp:201
int gpu_frame_buffer_size
Definition options.hpp:46
int stable_diffusion_steps
Definition options.hpp:58
double dream_zoom
Definition options.hpp:74
bool stable_diffusion_upscale_only
Definition options.hpp:148
bool constant_frame_rate
Definition options.hpp:100
std::string input_file
Definition options.hpp:171
int stable_diffusion_seed
Definition options.hpp:59
bool audio_pass_through
Definition options.hpp:111
bool enable_screenshot
Definition options.hpp:89
bool enable_random_autopilot
Definition options.hpp:91
bool use_source_fps
Definition options.hpp:83
int generate_interval
Definition options.hpp:36
std::string compute_shader
Definition options.hpp:175
std::string stable_diffusion_prompt
Definition options.hpp:200
double audio_sensitivity
Definition options.hpp:66
std::vector< std::string > entries
std::vector< CustomUniform > custom_uniforms
std::vector< std::uint16_t > rgba16
std::vector< std::uint8_t > rgba
std::vector< float > samples
std::vector< LayerMetadata > layers
unsigned char status
Definition midi.hpp:21
unsigned char data1
Definition midi.hpp:22
unsigned char data2
Definition midi.hpp:23
std::vector< unsigned char > bytes
Definition midi.hpp:14
std::vector< std::string > server_arguments