vulkan/screenshot-layer: Add Vulkan screenshot layer

This change adds a Vulkan screenshot layer that allows users to take
screenshots from a Vulkan application, but has an emphasis on
performance, decreasing the performance impact on the application
involved. This allows for automated setups to use this layer to take
screenshots for navigating various in-application menus.

This layer works by hooking into various common Vulkan setup functions, until
it enters the vkQueuePresentKHR function, and from there it copies the current
frame's image from the swapchain as an RGB image to host-cached memory, where
we will receive the information as a framebuffer pointer. From there, we copy
the framebuffer contents to a thread that will detach from the main process
so it can write the image to a PNG file without holding back the main thread.

This layer was created from using the existing overlay layer as a template,
then adding portions of LunarG's VulkanTools screenshot layer:
https://github.com/LunarG/VulkanTools/blob/main/layersvt/screenshot.cpp

More specifically, there were usages of functions, along with modifications of
various functions from screenshot.cpp in the VulkanTools project, used in
screenshot.cpp.

There are some sections of the screenshotting functionality that remain
unmodified from the original screenshot.cpp file in VulkanTools, including the
global locking structures and the writeFile() function, which takes care of
obtaining the images from the swapchain. There were various areas in which
modifications were made, including how images are written to a file (using PNG
instead of PPM, introducing threading, added fences/semaphores, etc), along
with many smaller changes.

v2: Fix segfault upon application exit

v3: Fix filename issue with concatenation, along with some leftover
memory handling that wasn't cleaned up.

v4: Fix some error handling and nits

v5: Fix output directory handling

Reviewed-by: Ivan Briano <ivan.briano@intel.com

Signed-off-by: Casey Bowman <casey.g.bowman@intel.com>
Part-of: <https://gitlab.freedesktop.org/mesa/mesa/-/merge_requests/30527>
This commit is contained in:
Casey Bowman
2024-05-29 23:39:45 -07:00
committed by Marge Bot
parent 7530487e60
commit eda55c7c2f
11 changed files with 2442 additions and 1 deletions

View File

@@ -59,6 +59,7 @@ with_glx_direct = get_option('glx-direct')
with_osmesa = get_option('osmesa')
with_vulkan_overlay_layer = get_option('vulkan-layers').contains('overlay')
with_vulkan_device_select_layer = get_option('vulkan-layers').contains('device-select')
with_vulkan_screenshot_layer = get_option('vulkan-layers').contains('screenshot')
with_tools = get_option('tools')
if with_tools.contains('all')
with_tools = [

View File

@@ -311,7 +311,7 @@ option(
'vulkan-layers',
type : 'array',
value : [],
choices : ['device-select', 'intel-nullhw', 'overlay'],
choices : ['device-select', 'intel-nullhw', 'overlay', 'screenshot'],
description : 'List of vulkan layers to build'
)

View File

@@ -88,3 +88,6 @@ endif
if with_vulkan_device_select_layer
subdir('device-select-layer')
endif
if with_vulkan_screenshot_layer
subdir('screenshot-layer')
endif

View File

@@ -0,0 +1,178 @@
The screenshot-layer directory was created from using mesa-overlay as a template, then
adding portions of the screenshotting layer from LunarG's VulkanTools repository:
https://github.com/LunarG/VulkanTools/tree/main
Included below is the original Apache 2.0 license included in VulkanTools.
===========================================================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction, and distribution as
defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner
that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all other entities that
control, are controlled by, or are under common control with that entity. For the
purposes of this definition, "control" means (i) the power, direct or indirect, to
cause the direction or management of such entity, whether by contract or otherwise,
or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or
(iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions
granted by this License.
"Source" form shall mean the preferred form for making modifications, including but not
limited to software source code, documentation source, and configuration files.
"Object" form shall mean any form resulting from mechanical transformation or
translation of a Source form, including but not limited to compiled object code,
generated documentation, and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or Object form, made
available under the License, as indicated by a copyright notice that is included in or
attached to the work (an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object form, that is based
on (or derived from) the Work and for which the editorial revisions, annotations,
elaborations, or other modifications represent, as a whole, an original work of
authorship. For the purposes of this License, Derivative Works shall not include works
that remain separable from, or merely link (or bind by name) to the interfaces of, the
Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including the original version of the
Work and any modifications or additions to that Work or Derivative Works thereof, that
is intentionally submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of the copyright owner.
For the purposes of this definition, "submitted" means any form of electronic, verbal,
or written communication sent to the Licensor or its representatives, including but not
limited to communication on electronic mailing lists, source code control systems, and
issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose
of discussing and improving the Work, but excluding communication that is conspicuously
marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a
Contribution has been received by Licensor and subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of this License, each
Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the Work and such
Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of this License, each
Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable (except as stated in this section) patent license to make,
have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such
license applies only to those patent claims licensable by such Contributor that are
necessarily infringed by their Contribution(s) alone or by combination of their
Contribution(s) with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a cross-claim or counterclaim
in a lawsuit) alleging that the Work or a Contribution incorporated within the Work
constitutes direct or contributory patent infringement, then any patent licenses granted
to You under this License for that Work shall terminate as of the date such litigation
is filed.
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative
Works thereof in any medium, with or without modifications, and in Source or Object form,
provided that You meet the following conditions:
You must give any other recipients of the Work or Derivative Works a copy of this
License; and
You must cause any modified files to carry prominent notices stating that You changed
the files; and
You must retain, in the Source form of any Derivative Works that You distribute, all
copyright, patent, trademark, and attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of the Derivative Works; and
If the Work includes a "NOTICE" text file as part of its distribution, then any
Derivative Works that You distribute must include a readable copy of the attribution
notices contained within such NOTICE file, excluding those notices that do not pertain
to any part of the Derivative Works, in at least one of the following places: within a
NOTICE text file distributed as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or, within a display
generated by the Derivative Works, if and wherever such third-party notices normally
appear. The contents of the NOTICE file are for informational purposes only and do not
modify the License. You may add Your own attribution notices within Derivative Works
that You distribute, alongside or as an addendum to the NOTICE text from the Work,
provided that such additional attribution notices cannot be construed as modifying
the License.
You may add Your own copyright statement to Your modifications and may provide
additional or different license terms and conditions for use, reproduction, or
distribution of Your modifications, or for any such Derivative Works as a whole,
provided Your use, reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution
intentionally submitted for inclusion in the Work by You to the Licensor shall be under
the terms and conditions of this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify the terms of any
separate license agreement you may have executed with Licensor regarding such
Contributions.
6. Trademarks. This License does not grant permission to use the trade names,
trademarks, service marks, or product names of the Licensor, except as required for
reasonable and customary use in describing the origin of the Work and reproducing the
content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing,
Licensor provides the Work (and each Contributor provides its Contributions) on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT,
MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for
determining the appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory, whether in tort
(including negligence), contract, or otherwise, unless required by applicable law (such
as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor
be liable to You for damages, including any direct, indirect, special, incidental, or
consequential damages of any character arising as a result of this License or out of the
use or inability to use the Work (including but not limited to damages for loss of
goodwill, work stoppage, computer failure or malfunction, or any and all other
commercial damages or losses), even if such Contributor has been advised of the
possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing the Work or
Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of
support, warranty, indemnity, or other liability obligations and/or rights consistent
with this License. However, in accepting such obligations, You may act only on Your own
behalf and on Your sole responsibility, not on behalf of any other Contributor, and only
if You agree to indemnify, defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason of your accepting
any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: HOW TO APPLY THE APACHE LICENSE TO YOUR WORK
To apply the Apache License to your work, attach the following boilerplate notice, with
the fields enclosed by brackets "[]" replaced with your own identifying information.
(Don't include the brackets!) The text should be enclosed in the appropriate comment
syntax for the file format. We also recommend that a file or class name and description
of purpose be included on the same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@@ -0,0 +1,87 @@
A Vulkan layer to display information about the running application using an overlay.
Building
========
The overlay layer will be built if :code:`screenshot` is passed as a :code:`vulkan-layers` argument. For example:
.. code-block:: sh
meson -Dvulkan-layers=device-select,screenshot builddir/
ninja -C builddir/
sudo ninja -C builddir/ install
See `docs/install.rst <https://gitlab.freedesktop.org/mesa/mesa/-/blob/master/docs/install.rst>`__ for more information.
Basic Usage
===========
Turn on the layer:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot /path/to/my_vulkan_app
List the help menu:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=help /path/to/my_vulkan_app
Enable log output in stdout/stderr:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=log_type=<info|debug> /path/to/my_vulkan_app
Redirect screenshots taken to a different directory:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=output_dir=/path/to/new_dir /path/to/my_vulkan_app
Capture pre-determined screenshots:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=frames=1/5/7/15-4-5 /path/to/my_vulkan_app
Note:
- Individual frames are separated by '/' and must be listed before the frame range
- The frame range is determined by <range start>-<range count>-<range interval>
- Example: '1/5/7/15-4-5' gives individual frames [1,5,7], then the frame range gives [15,20,25,30], combining into [1,5,7,15,20,25,30]
To capture all frames:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=frames=all /path/to/my_vulkan_app
Direct Socket Control
---------------------
Enabling communication with the client can be done with the following setup:
.. code-block:: sh
VK_LOADER_LAYERS_ENABLE=VK_LAYER_MESA_screenshot VK_LAYER_MESA_SCREENSHOT_CONFIG=comms /path/to/my_vulkan_app
The Unix socket may be used directly if needed. Once a client connects to the socket, the overlay layer will immediately
send the following commands to the client:
.. code-block:: sh
:MesaOverlayControlVersion=1;
:DeviceName=<device name>;
:MesaVersion=<mesa version>;
The client connected to the overlay layer can trigger a screenshot to be taken by sending the command:
.. code-block:: sh
:capture=<screenshot_name.png>;
Note that the screenshot name must include '.png', other image types are not supported.
.. _docs/install.rst: ../../docs/install.rst

View File

@@ -0,0 +1,11 @@
{
"file_format_version" : "1.0.0",
"layer" : {
"name": "VK_LAYER_MESA_screenshot",
"type": "GLOBAL",
"library_path": "libVkLayer_MESA_screenshot.so",
"api_version": "1.3.211",
"implementation_version": "1",
"description": "Mesa Screenshot layer"
}
}

View File

@@ -0,0 +1,200 @@
#!/usr/bin/env python3
import socket
import sys
import select
from select import EPOLLIN, EPOLLPRI, EPOLLERR
import time
import argparse
TIMEOUT = 1.0 # seconds
VERSION_HEADER = bytearray('MesaScreenshotControlVersion', 'utf-8')
DEVICE_NAME_HEADER = bytearray('DeviceName', 'utf-8')
MESA_VERSION_HEADER = bytearray('MesaVersion', 'utf-8')
DEFAULT_SERVER_ADDRESS = "\0mesa_screenshot"
class Connection:
def __init__(self, path):
# Create a Unix Domain socket and connect
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
try:
sock.connect(path)
except socket.error as msg:
print(msg)
sys.exit(1)
self.sock = sock
# initialize poll interface and register socket
epoll = select.epoll()
epoll.register(sock, EPOLLIN | EPOLLPRI | EPOLLERR)
self.epoll = epoll
def recv(self, timeout):
'''
timeout as float in seconds
returns:
- None on error or disconnection
- bytes() (empty) on timeout
'''
events = self.epoll.poll(timeout)
for ev in events:
(fd, event) = ev
if fd != self.sock.fileno():
continue
# check for socket error
if event & EPOLLERR:
return None
# EPOLLIN or EPOLLPRI, just read the message
msg = self.sock.recv(4096)
# socket disconnected
if len(msg) == 0:
return None
return msg
return bytes()
def send(self, msg):
self.sock.send(msg)
class MsgParser:
MSGBEGIN = bytes(':', 'utf-8')[0]
MSGEND = bytes(';', 'utf-8')[0]
MSGSEP = bytes('=', 'utf-8')[0]
def __init__(self, conn):
self.cmdpos = 0
self.parampos = 0
self.bufferpos = 0
self.reading_cmd = False
self.reading_param = False
self.buffer = None
self.cmd = bytearray(4096)
self.param = bytearray(4096)
self.conn = conn
def readCmd(self, ncmds, timeout=TIMEOUT):
'''
returns:
- None on error or disconnection
- bytes() (empty) on timeout
'''
parsed = []
remaining = timeout
while remaining > 0 and ncmds > 0:
now = time.monotonic()
if self.buffer is None:
self.buffer = self.conn.recv(remaining)
self.bufferpos = 0
# disconnected or error
if self.buffer is None:
return None
for i in range(self.bufferpos, len(self.buffer)):
c = self.buffer[i]
self.bufferpos += 1
if c == self.MSGBEGIN:
self.cmdpos = 0
self.parampos = 0
self.reading_cmd = True
self.reading_param = False
elif c == self.MSGEND:
if not self.reading_cmd:
continue
self.reading_cmd = False
self.reading_param = False
cmd = self.cmd[0:self.cmdpos]
param = self.param[0:self.parampos]
self.reading_cmd = False
self.reading_param = False
parsed.append((cmd, param))
ncmds -= 1
if ncmds == 0:
break
elif c == self.MSGSEP:
if self.reading_cmd:
self.reading_param = True
else:
if self.reading_param:
self.param[self.parampos] = c
self.parampos += 1
elif self.reading_cmd:
self.cmd[self.cmdpos] = c
self.cmdpos += 1
# if we read the entire buffer and didn't finish the command,
# throw it away
self.buffer = None
# check if we have time for another iteration
elapsed = time.monotonic() - now
remaining = max(0, remaining - elapsed)
# timeout
return parsed
def control(args):
if args.socket:
address = '\0' + args.socket
else:
address = DEFAULT_SERVER_ADDRESS
conn = Connection(address)
msgparser = MsgParser(conn)
version = None
name = None
mesa_version = None
msgs = msgparser.readCmd(3)
for m in msgs:
cmd, param = m
if cmd == VERSION_HEADER:
version = int(param)
elif cmd == DEVICE_NAME_HEADER:
name = param.decode('utf-8')
elif cmd == MESA_VERSION_HEADER:
mesa_version = param.decode('utf-8')
if version != 1 or name is None or mesa_version is None:
print('ERROR: invalid protocol')
sys.exit(1)
if args.info:
print(f"Protocol Version: {version}")
print(f"Device Name: {name}")
print(f"Mesa Version: {mesa_version}")
if args.cmd == 'capture':
if args.filename is None:
args.filename = ''
msg = ':capture=' + args.filename + ';'
conn.send(bytearray(msg, 'utf-8'))
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='MESA_screenshot control client')
parser.add_argument('--info', action='store_true', help='Print info from socket')
parser.add_argument('--socket', '-s', type=str, help='Path to socket')
commands = parser.add_subparsers(help='commands to run', dest='cmd')
commands_parser = commands.add_parser('capture', help='capture [filename.png]')
commands_parser.add_argument('filename', nargs='?', type=str)
args = parser.parse_args()
control(args)

View File

@@ -0,0 +1,47 @@
# Copyright © 2019 Intel Corporation
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
vklayer_files = files(
'screenshot.cpp',
'screenshot_params.c',
)
vklayer_mesa_screenshot = shared_library(
'VkLayer_MESA_screenshot',
vklayer_files, sha1_h,
c_args : [no_override_init_args],
gnu_symbol_visibility : 'hidden',
dependencies : [idep_vulkan_util, idep_mesautil, vulkan_wsi_deps, dep_dl, dependency('libpng')],
include_directories : [inc_include, inc_src],
link_args : cc.get_supported_link_arguments(['-Wl,-Bsymbolic-functions', '-Wl,-z,relro']),
install : true
)
install_data(
files('VkLayer_MESA_screenshot.json'),
install_dir : join_paths(get_option('datadir'), 'vulkan', 'explicit_layer.d'),
install_tag : 'runtime',
)
install_data(
'mesa-screenshot-control.py',
install_dir : get_option('bindir'),
install_mode : 'r-xr-xr-x',
)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,414 @@
/*
* Copyright © 2024 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#include <assert.h>
#include <ctype.h>
#include <dirent.h>
#include <stdio.h>
#include <string.h>
#include <stdarg.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "screenshot_params.h"
#include "util/os_socket.h"
enum LogType LOG_TYPE = REQUIRED;
static const char *print_log_type(enum LogType log_type) {
switch(log_type)
{
case(DEBUG):
return "DEBUG";
case(ERROR):
return "ERROR";
case(INFO):
return "INFO";
case(NO_PREFIX):
return "NO_PREFIX";
case(REQUIRED):
return "REQUIRED";
case(WARN):
return "WARN";
default:
/* Don't show log type*/
return "";
}
}
void LOG(enum LogType log_type, const char *format, ...) {
FILE *file_type;
va_list args;
if (log_type == WARN || log_type == ERROR) {
file_type = stderr;
} else {
file_type = stdout;
}
if (log_type == DEBUG && LOG_TYPE != DEBUG) {
return;
} else if (log_type == INFO && (LOG_TYPE != INFO && LOG_TYPE != DEBUG)) {
return;
}
if (log_type != NO_PREFIX)
fprintf(file_type, "mesa-screenshot: %s: ", print_log_type(log_type));
va_start(args, format);
vfprintf(file_type, format, args);
va_end(args);
}
static const char *
parse_control(const char *str)
{
static char control_str[64];
if (strlen(str) > 63) {
LOG(ERROR, "control string too long. Must be < 64 chars\n");
return NULL;
}
strcpy(control_str, str);
return control_str;
}
/* Inserts frame nodes in ascending order */
static void insert_frame(struct frame_list *list, uint32_t new_frame_num)
{
struct frame_node *new_node, *curr, *next;
new_node = (struct frame_node*)malloc(sizeof(struct frame_node));
new_node->frame_num = new_frame_num;
new_node->next = NULL;
curr = list->head;
/* Empty list */
if (list->head == NULL)
list->head = new_node;
/* Insert as new head of list */
else if (list->head->frame_num > new_frame_num) {
list->head = new_node;
new_node->next = curr;
/* Traverse list & insert frame number in correct, ascending location */
} else {
while (curr != NULL) {
if (curr->frame_num == new_frame_num) {
free(new_node);
return; // Avoid inserting duplicates
}
next = curr->next;
if (next) {
if (next->frame_num > new_frame_num) {
curr->next = new_node;
new_node->next = next;
break;
}
} else {
curr->next = new_node;
break;
}
curr = curr->next;
}
}
list->size++;
}
void remove_node(struct frame_list *list,
struct frame_node *prev,
struct frame_node *node) {
if (node) {
if (prev)
prev->next = node->next;
else {
list->head = node->next;
}
free(node);
list->size--;
} else
LOG(ERROR, "Encountered null node while removing from frame list\n");
}
void destroy_frame_list(struct frame_list *list)
{
struct frame_node *curr, *prev;
if (!list || !list->head)
return;
else {
curr = list->head;
while (curr != NULL) {
prev = curr;
curr = curr->next;
free(prev);
}
}
}
static unsigned
parse_unsigned(const char *str)
{
return strtol(str, NULL, 0);
}
static bool is_frame_delimiter(char c)
{
return c == 0 || c == '/' || c == '-';
}
static struct frame_list *
parse_frames(const char *str)
{
int32_t range_start;
uint32_t range_counter, range_interval, range_end;
range_start = -1;
range_counter = 0;
uint32_t range_delimit_count = 0;
range_interval = 1;
char *prev_delim = NULL;
char str_buf[256] = {0};
char *str_buf_ptr;
str_buf_ptr = str_buf;
struct frame_list *list = (struct frame_list*)malloc(sizeof(struct frame_list));
list->size = 0;
list->all_frames = false;
if (!strcmp(str, "all")) {
/* Don't bother counting, we want all frames */
list->all_frames = true;
} else {
while (*str != 0) { // Still string left to parse
for (; !is_frame_delimiter(*str); str++, str_buf_ptr++) {
if (!isdigit(*str))
{
LOG(ERROR, "mesa-screenshot: syntax error: unexpected non-digit "
"'%c' while parsing the frame numbers\n", *str);
destroy_frame_list(list);
return NULL;
}
*str_buf_ptr = *str;
}
if (strlen(str_buf) == 0) {
LOG(ERROR, "mesa-screenshot: syntax error: empty string given in frame range\n");
return NULL;
} else if (strlen(str_buf) > 0 && *str == '/') {
if (prev_delim && *prev_delim == '-') {
LOG(ERROR, "mesa-screenshot: syntax error: detected invalid individual " \
"frame selection (/) after range selection (-)\n");
return NULL;
}
LOG(DEBUG, "Adding frame: %u\n", parse_unsigned(str_buf));
insert_frame(list, parse_unsigned(str_buf));
} else if (strlen(str_buf) > 0 && (*str == '-' || *str == 0 )) {
if (range_delimit_count < 1) {
LOG(DEBUG, "Range start set\n");
range_start = parse_unsigned(str_buf);
range_delimit_count++;
} else if(range_delimit_count < 2) {
LOG(DEBUG, "Range counter set\n");
range_counter = parse_unsigned(str_buf);
range_delimit_count++;
} else {
LOG(DEBUG, "Range interval set\n");
range_interval = parse_unsigned(str_buf);
break;
}
if (*str == 0) {
break;
}
prev_delim = (char *)str;
}
str++;
/* Reset buffer for next set of numbers */
memset(str_buf, '\0', sizeof(str_buf));
str_buf_ptr = str_buf;
}
range_end = range_start + (range_counter * range_interval);
if (range_start >= 0) {
int i = range_start;
do {
insert_frame(list, i);
i += range_interval;
} while (i < range_end);
}
}
LOG(INFO, "frame range: ");
if (list->all_frames) {
LOG(NO_PREFIX, "all");
} else {
for (struct frame_node *iter = list->head; iter != NULL; iter = iter->next) {
LOG(NO_PREFIX, "%u", iter->frame_num);
if(iter->next) {
LOG(NO_PREFIX, ", ");
}
}
}
LOG(NO_PREFIX, "\n");
return list;
}
static bool
parse_help(const char *str)
{
LOG(NO_PREFIX, "Layer params using VK_LAYER_MESA_SCREENSHOT_CONFIG=\n");
#define SCREENSHOT_PARAM_BOOL(name) \
LOG(NO_PREFIX, "\t%s=0|1\n", #name);
#define SCREENSHOT_PARAM_CUSTOM(name)
SCREENSHOT_PARAMS
#undef SCREENSHOT_PARAM_BOOL
#undef SCREENSHOT_PARAM_CUSTOM
LOG(NO_PREFIX, "\tlog_type=info|debug (if no selection, no logs besides errors are given)\n");
LOG(NO_PREFIX, "\toutput_dir='/path/to/dir'\n");
LOG(NO_PREFIX, "\tframes=Individual frames, separated by '/', followed by " \
"a range setup, separated by '-', <range start>-<range count>-<range interval>\n" \
"\tFor example '1/5/7/15-4-5' = [1,5,7,15,20,25,30]\n" \
"\tframes='all' will select all frames.");
return true;
}
static enum LogType
parse_log_type(const char *str)
{
if(!strcmp(str, "info")) {
return INFO;
} else if (!strcmp(str, "debug")) {
return DEBUG;
} else {
/* Required logs only */
return REQUIRED;
}
}
/* TODO: Improve detection of proper directory path */
static const char *
parse_output_dir(const char *str)
{
static char output_dir[256];
strcpy(output_dir, str);
uint32_t last_char_index = strlen(str)-1;
// Ensure we're in bounds and the last character is '/'
if (last_char_index > 0 &&
str[last_char_index] != '/' &&
last_char_index < 254) {
output_dir[last_char_index+1] = '/';
}
DIR *dir = opendir(output_dir);
assert(dir);
closedir(dir);
return output_dir;
}
static bool is_delimiter(char c)
{
return c == 0 || c == ',' || c == ':' || c == ';' || c == '=';
}
static int
parse_string(const char *s, char *out_param, char *out_value)
{
int i = 0;
for (; !is_delimiter(*s); s++, out_param++, i++)
*out_param = *s;
*out_param = 0;
if (*s == '=') {
s++;
i++;
for (; !is_delimiter(*s); s++, out_value++, i++)
*out_value = *s;
} else
*(out_value++) = '1';
*out_value = 0;
if (*s && is_delimiter(*s)) {
s++;
i++;
}
if (*s && !i) {
LOG(ERROR, "mesa-screenshot: syntax error: unexpected '%c' (%i) while "
"parsing a string\n", *s, *s);
}
return i;
}
const char *screenshot_param_names[] = {
#define SCREENSHOT_PARAM_BOOL(name) #name,
#define SCREENSHOT_PARAM_CUSTOM(name)
SCREENSHOT_PARAMS
#undef SCREENSHOT_PARAM_BOOL
#undef SCREENSHOT_PARAM_CUSTOM
};
void
parse_screenshot_env(struct screenshot_params *params,
const char *env)
{
if (!env)
return;
uint32_t num;
const char *itr = env;
char key[256], value[256];
memset(params, 0, sizeof(*params));
params->control = "mesa_screenshot";
params->frames = NULL;
params->output_dir = NULL;
/* Loop once first until log options found (if they exist) */
while ((num = parse_string(itr, key, value)) != 0) {
itr += num;
if (!strcmp("log_type", key)) {
LOG_TYPE = parse_log_type(value);
break;
}
}
/* Reset the iterator */
itr = env;
while ((num = parse_string(itr, key, value)) != 0) {
itr += num;
if (!strcmp("log_type", key)) {
/* Skip if matched again*/
continue;
}
#define SCREENSHOT_PARAM_BOOL(name) \
if (!strcmp(#name, key)) { \
params->enabled[SCREENSHOT_PARAM_ENABLED_##name] = \
strtol(value, NULL, 0); \
continue; \
}
#define SCREENSHOT_PARAM_CUSTOM(name) \
if (!strcmp(#name, key)) { \
params->name = parse_##name(value); \
continue; \
}
SCREENSHOT_PARAMS
#undef SCREENSHOT_PARAM_BOOL
#undef SCREENSHOT_PARAM_CUSTOM
LOG(ERROR, "Unknown option '%s'\n", key);
}
}

View File

@@ -0,0 +1,98 @@
/*
* Copyright © 2024 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#ifndef SCREENSHOT_PARAMS_H
#define SCREENSHOT_PARAMS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#define SCREENSHOT_PARAMS \
SCREENSHOT_PARAM_BOOL(comms) \
SCREENSHOT_PARAM_CUSTOM(control) \
SCREENSHOT_PARAM_CUSTOM(frames) \
SCREENSHOT_PARAM_CUSTOM(log_type) \
SCREENSHOT_PARAM_CUSTOM(output_dir) \
SCREENSHOT_PARAM_CUSTOM(help)
enum screenshot_param_enabled {
#define SCREENSHOT_PARAM_BOOL(name) SCREENSHOT_PARAM_ENABLED_##name,
#define SCREENSHOT_PARAM_CUSTOM(name)
SCREENSHOT_PARAMS
#undef SCREENSHOT_PARAM_BOOL
#undef SCREENSHOT_PARAM_CUSTOM
SCREENSHOT_PARAM_ENABLED_MAX
};
enum LogType {
DEBUG,
ERROR,
INFO,
NO_PREFIX, // Don't prefix the log with text
REQUIRED, // Non-error logs that must be printed for user
WARN
};
extern enum LogType LOG_TYPE;
struct frame_node {
uint32_t frame_num;
struct frame_node *next;
};
/* List should be sorted into ascending order, in terms of frame_node data */
struct frame_list {
uint32_t size;
bool all_frames;
struct frame_node *head;
};
void remove_node(struct frame_list *, struct frame_node *, struct frame_node *);
void destroy_frame_list(struct frame_list *);
void LOG(enum LogType, const char *, ...);
struct screenshot_params {
bool enabled[SCREENSHOT_PARAM_ENABLED_MAX];
struct frame_list *frames;
const char *control;
enum LogType log_type;
const char *output_dir;
bool help;
};
const extern char *screenshot_param_names[];
void parse_screenshot_env(struct screenshot_params *params,
const char *env);
#ifdef __cplusplus
}
#endif
#endif /* SCREENSHOT_PARAMS_H */