3 # Copyright (c) 2014, 2016-2017, 2019-2020 Intel Corporation
4 # Copyright © 2019, 2021 Collabora Ltd.
5 # Copyright © 2019-2020 Valve Corporation.
7 # Permission is hereby granted, free of charge, to any person obtaining a
8 # copy of this software and associated documentation files (the "Software"),
9 # to deal in the Software without restriction, including without limitation
10 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
11 # and/or sell copies of the Software, and to permit persons to whom the
12 # Software is furnished to do so, subject to the following conditions:
14 # The above copyright notice and this permission notice shall be included
15 # in all copies or substantial portions of the Software.
17 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
21 # OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
22 # ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
23 # OTHER DEALINGS IN THE SOFTWARE.
25 # SPDX-License-Identifier: MIT
28 """ Module providing an apitrace dump backend for replayer """
34 from framework
import core
, exceptions
36 from .abstract
import DumpBackend
, dump_handler
37 from .register
import Registry
39 _LOOP_TIMES
= core
.get_option('PIGLIT_REPLAY_LOOP_TIMES',
40 ('replay', 'loop_times'),
49 def _collect_frame_times(stream
):
51 - `stream` Output stream of `apitrace replay` with the `--pframes "opengl:GPU Duration"` option enabled.
52 - `return` The frame times collected from parsing the stream.
54 assert len(stream
) > 0
55 # Store frame times as we read lines
59 # Look for frame events
60 if not line
.startswith('frame'):
62 # Lines of the form "frame 22156000"
63 fields
= line
.rstrip('\r\n').split('\t')
64 frame_time
= int(fields
[1])
65 frame_times
.append(frame_time
)
67 return frame_times
[-int(_LOOP_TIMES
):]
70 def _run_command(cmd
: str, env
: dict) -> subprocess
.CompletedProcess
:
71 ret
: subprocess
.CompletedProcess
= subprocess
.run(
72 cmd
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
, env
=env
74 logoutput
= f
"[profile_trace] Running: {' '.join(cmd)}\n".encode()
75 print(logoutput
.decode(errors
='replace'))
77 # Print the command logs if the process returns with an error code.
78 stdout
= ret
.stdout
.decode(errors
="replace")
79 print(f
"[profile_trace] {stdout}")
80 stderr
= ret
.stderr
.decode(errors
="replace")
81 print(f
"[profile_trace] {stderr}")
83 f
'[profile_trace] Process failed with error code: {ret.returncode}'
88 class APITraceBackend(DumpBackend
):
89 """ replayer's apitrace dump backend
91 This backend uses apitrace for replaying its traces.
93 It supports OpenGL/ES traces, to be replayed with eglretrace, and DXGI
94 traces, to be replayed with d3dretrace on Wine.
96 However, the binary paths to the apitrace, eglretrace, d3dretrace and wine
97 binaries are configurable. Hence, using wine could be omitted, for example.
101 def __init__(self
, trace_path
, output_dir
=None, calls
=None, **kwargs
):
102 super(APITraceBackend
, self
).__init
__(trace_path
, output_dir
, calls
,
104 extension
= path
.splitext(self
._trace
_path
)[1]
106 if extension
== '.trace':
107 eglretrace_bin
= core
.get_option('PIGLIT_REPLAY_EGLRETRACE_BINARY',
108 ('replay', 'eglretrace_bin'),
109 default
='eglretrace')
110 self
._retrace
_cmd
= [eglretrace_bin
]
111 elif extension
== '.trace-dxgi':
112 wine_bin
= core
.get_option('PIGLIT_REPLAY_WINE_BINARY',
113 ('replay', 'wine_bin'),
115 wine_d3dretrace_bin
= core
.get_option(
116 'PIGLIT_REPLAY_WINE_D3DRETRACE_BINARY',
117 ('replay', 'wine_d3dretrace_bin'),
118 default
='d3dretrace')
119 self
._retrace
_cmd
= [wine_bin
, wine_d3dretrace_bin
]
121 raise exceptions
.PiglitFatalError(
122 'Invalid trace_path: "{}" tried to be dumped '
123 'by the APITraceBackend.\n'.format(self
._trace
_path
))
125 def _get_last_frame_call(self
):
126 cmd_wrapper
= self
._retrace
_cmd
[:-1]
128 apitrace_bin
= core
.get_option(
129 'PIGLIT_REPLAY_WINE_APITRACE_BINARY',
130 ('replay', 'wine_apitrace_bin'),
133 apitrace_bin
= core
.get_option('PIGLIT_REPLAY_APITRACE_BINARY',
134 ('replay', 'apitrace_bin'),
136 cmd
= cmd_wrapper
+ [apitrace_bin
,
137 'dump', '--calls=frame', self
._trace
_path
]
138 ret
= subprocess
.run(cmd
, stdout
=subprocess
.PIPE
, stderr
=sys
.stderr
)
139 logoutput
= '[dump_trace_images] Running: {}\n'.format(
140 ' '.join(cmd
)) + ret
.stdout
.decode(errors
='replace')
142 for line
in reversed(ret
.stdout
.decode(errors
='replace').splitlines()):
143 split
= line
.split(None, 1)
144 if split
and split
[0].isnumeric():
150 outputprefix
= '{}-'.format(path
.join(self
._output
_dir
,
151 path
.basename(self
._trace
_path
)))
153 self
._calls
= [str(self
._get
_last
_frame
_call
())]
154 if core
.get_option('PIGLIT_REPLAY_OPTIONS', ('replay', 'options'), default
=None) is not None:
155 self
._retrace
_cmd
+= [core
.get_option('PIGLIT_REPLAY_OPTIONS', ('replay', 'options'))]
156 cmd
= self
._retrace
_cmd
+ ['--headless',
157 '--snapshot=' + ','.join(self
._calls
),
158 '--snapshot-prefix=' + outputprefix
,
160 self
._run
_logged
_command
(cmd
, None)
163 def profile(trace_path
):
164 return APITraceBackend(trace_path
)._profile
()
167 # We need to run in singlethread mode to avoid a use after free bug
168 # in which the OpenGL context is queried for further results after
169 # it has been destroyed in the replay thread when replay finishes
170 cmd
= self
._retrace
_cmd
+ ['--headless',
173 '--loop=%s' % _LOOP_TIMES
,
175 'opengl:GPU Duration',
177 ret
= _run_command(cmd
, None)
178 return _collect_frame_times(ret
.stdout
.decode().splitlines())
182 extensions
=['.trace', '.trace-dxgi'],
183 backend
=APITraceBackend
,