17 from distutils.sysconfig import get_python_lib
18 from distutils.util import strtobool
20 from scripts.common import get_meson
21 from scripts.common import git
22 from scripts.common import win32_get_short_path_name
23 from scripts.common import get_wine_shortpath
25 SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
26 PREFIX_DIR = os.path.join(SCRIPTDIR, 'prefix')
27 # Use '_build' as the builddir instead of 'build'
28 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, 'build')
29 if not os.path.exists(DEFAULT_BUILDDIR):
30 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, '_build')
32 TYPELIB_REG = re.compile(r'.*\.typelib$')
33 SHAREDLIB_REG = re.compile(r'\.so|\.dylib|\.dll')
35 # libdir is expanded from option of the same name listed in the `meson
36 # introspect --buildoptions` output.
37 GSTPLUGIN_FILEPATH_REG_TEMPLATE = r'.*/{libdir}/gstreamer-1.0/[^/]+$'
38 GSTPLUGIN_FILEPATH_REG = None
41 if isinstance(o, str):
43 if isinstance(o, list):
45 raise AssertionError('Object {!r} must be a string or a list'.format(o))
48 if isinstance(o, str):
50 if isinstance(o, list):
53 raise AssertionError('Did not expect object {!r} to have more than one element'.format(o))
54 raise AssertionError('Object {!r} must be a string or a list'.format(o))
56 def prepend_env_var(env, var, value, sysroot):
57 if value.startswith(sysroot):
58 value = value[len(sysroot):]
59 # Try not to exceed maximum length limits for env vars on Windows
61 value = win32_get_short_path_name(value)
62 env_val = env.get(var, '')
63 val = os.pathsep + value + os.pathsep
64 # Don't add the same value twice
65 if val in env_val or env_val.startswith(value + os.pathsep):
67 env[var] = val + env_val
68 env[var] = env[var].replace(os.pathsep + os.pathsep, os.pathsep).strip(os.pathsep)
70 def is_library_target_and_not_plugin(target, filename):
72 Don't add plugins to PATH/LD_LIBRARY_PATH because:
74 2. It causes us to exceed the PATH length limit on Windows and Wine
76 if not target['type'].startswith('shared'):
78 if not target['installed']:
80 # Check if this output of that target is a shared library
81 if not SHAREDLIB_REG.search(filename):
83 # Check if it's installed to the gstreamer plugin location
84 for install_filename in listify(target['install_filename']):
85 if install_filename.endswith(os.path.basename(filename)):
88 # None of the installed files in the target correspond to the built
92 global GSTPLUGIN_FILEPATH_REG
93 if GSTPLUGIN_FILEPATH_REG is None:
94 GSTPLUGIN_FILEPATH_REG = re.compile(GSTPLUGIN_FILEPATH_REG_TEMPLATE)
95 if GSTPLUGIN_FILEPATH_REG.search(install_filename.replace('\\', '/')):
100 def get_wine_subprocess_env(options, env):
101 with open(os.path.join(options.builddir, 'meson-info', 'intro-buildoptions.json')) as f:
102 buildoptions = json.load(f)
104 prefix, = [o for o in buildoptions if o['name'] == 'prefix']
105 path = os.path.normpath(os.path.join(prefix['value'], 'bin'))
106 prepend_env_var(env, "PATH", path, options.sysroot)
107 wine_path = get_wine_shortpath(
108 options.wine.split(' '),
109 [path] + env.get('WINEPATH', '').split(';')
112 wine_path += ';' + options.winepath
113 env['WINEPATH'] = wine_path
114 env['WINEDEBUG'] = 'fixme-all'
119 def get_subprocess_env(options, gst_version):
120 env = os.environ.copy()
122 env["CURRENT_GST"] = os.path.normpath(SCRIPTDIR)
123 env["GST_VERSION"] = gst_version
124 env["GST_VALIDATE_SCENARIOS_PATH"] = os.path.normpath(
125 "%s/subprojects/gst-devtools/validate/data/scenarios" % SCRIPTDIR)
126 env["GST_VALIDATE_PLUGIN_PATH"] = os.path.normpath(
127 "%s/subprojects/gst-devtools/validate/plugins" % options.builddir)
128 env["GST_VALIDATE_APPS_DIR"] = os.path.normpath(
129 "%s/subprojects/gst-editing-services/tests/validate" % SCRIPTDIR)
130 env["GST_ENV"] = 'gst-' + gst_version
131 env["GST_REGISTRY"] = os.path.normpath(options.builddir + "/registry.dat")
132 prepend_env_var(env, "PATH", os.path.normpath(
133 "%s/subprojects/gst-devtools/validate/tools" % options.builddir),
137 return get_wine_subprocess_env(options, env)
139 prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'meson'),
142 env["GST_PLUGIN_SYSTEM_PATH"] = ""
143 env["GST_PLUGIN_SCANNER"] = os.path.normpath(
144 "%s/subprojects/gstreamer/libs/gst/helpers/gst-plugin-scanner" % options.builddir)
145 env["GST_PTP_HELPER"] = os.path.normpath(
146 "%s/subprojects/gstreamer/libs/gst/helpers/gst-ptp-helper" % options.builddir)
149 lib_path_envvar = 'PATH'
150 elif platform.system() == 'Darwin':
151 lib_path_envvar = 'DYLD_LIBRARY_PATH'
153 lib_path_envvar = 'LD_LIBRARY_PATH'
155 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(SCRIPTDIR, 'subprojects',
156 'gst-python', 'plugin'),
158 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(PREFIX_DIR, 'lib',
161 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, 'subprojects',
164 prepend_env_var(env, "GST_VALIDATE_SCENARIOS_PATH",
165 os.path.join(PREFIX_DIR, 'share', 'gstreamer-1.0',
166 'validate', 'scenarios'),
168 prepend_env_var(env, "GI_TYPELIB_PATH", os.path.join(PREFIX_DIR, 'lib',
169 'lib', 'girepository-1.0'),
171 prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(PREFIX_DIR, 'lib', 'pkgconfig'),
175 prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'gstreamer', 'tools'),
178 # tools: gst-launch-1.0, gst-inspect-1.0
179 prepend_env_var(env, "PATH", os.path.join(options.builddir, 'subprojects',
180 'gstreamer', 'tools'),
182 prepend_env_var(env, "PATH", os.path.join(options.builddir, 'subprojects',
183 'gst-plugins-base', 'tools'),
186 # Library and binary search paths
187 prepend_env_var(env, "PATH", os.path.join(PREFIX_DIR, 'bin'),
189 if lib_path_envvar != 'PATH':
190 prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib'),
192 prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib64'),
194 elif 'QMAKE' in os.environ:
195 # There's no RPATH on Windows, so we need to set PATH for the qt5 DLLs
196 prepend_env_var(env, 'PATH', os.path.dirname(os.environ['QMAKE']),
200 targets_s = subprocess.check_output(meson + ['introspect', options.builddir, '--targets'])
201 targets = json.loads(targets_s.decode())
204 srcdir_path = pathlib.Path(options.srcdir)
206 build_options_s = subprocess.check_output(meson + ['introspect', options.builddir, '--buildoptions'])
207 build_options = json.loads(build_options_s.decode())
208 libdir, = [o['value'] for o in build_options if o['name'] == 'libdir']
209 libdir = libdir.replace('\\', '/')
211 global GSTPLUGIN_FILEPATH_REG_TEMPLATE
212 GSTPLUGIN_FILEPATH_REG_TEMPLATE = GSTPLUGIN_FILEPATH_REG_TEMPLATE.format(libdir=libdir)
214 for target in targets:
215 filenames = listify(target['filename'])
216 for filename in filenames:
217 root = os.path.dirname(filename)
218 if srcdir_path / "subprojects/gst-devtools/validate/plugins" in (srcdir_path / root).parents:
220 if filename.endswith('.dll'):
221 mono_paths.add(os.path.join(options.builddir, root))
222 if TYPELIB_REG.search(filename):
223 prepend_env_var(env, "GI_TYPELIB_PATH",
224 os.path.join(options.builddir, root),
226 elif is_library_target_and_not_plugin(target, filename):
227 prepend_env_var(env, lib_path_envvar,
228 os.path.join(options.builddir, root),
230 elif target['type'] == 'executable' and target['installed']:
231 paths.add(os.path.join(options.builddir, root))
233 with open(os.path.join(options.builddir, 'GstPluginsPath.json')) as f:
234 for plugin_path in json.load(f):
235 prepend_env_var(env, 'GST_PLUGIN_PATH', plugin_path,
239 prepend_env_var(env, 'PATH', p, options.sysroot)
243 prepend_env_var(env, "MONO_PATH", p, options.sysroot)
246 encoding_targets = set()
248 python_dirs = set(["%s/subprojects/gstreamer/libs/gst/helpers/" % options.srcdir])
249 if '--installed' in subprocess.check_output(meson + ['introspect', '-h']).decode():
250 installed_s = subprocess.check_output(meson + ['introspect', options.builddir, '--installed'])
251 for path, installpath in json.loads(installed_s.decode()).items():
252 installpath_parts = pathlib.Path(installpath).parts
253 path_parts = pathlib.Path(path).parts
255 # We want to add all python modules to the PYTHONPATH
256 # in a manner consistent with the way they would be imported:
257 # For example if the source path /home/meh/foo/bar.py
258 # is to be installed in /usr/lib/python/site-packages/foo/bar.py,
259 # we want to add /home/meh to the PYTHONPATH.
260 # This will only work for projects where the paths to be installed
261 # mirror the installed directory layout, for example if the path
262 # is /home/meh/baz/bar.py and the install path is
263 # /usr/lib/site-packages/foo/bar.py , we will not add anything
264 # to PYTHONPATH, but the current approach works with pygobject
265 # and gst-python at least.
266 if 'site-packages' in installpath_parts:
267 install_subpath = os.path.join(*installpath_parts[installpath_parts.index('site-packages') + 1:])
268 if path.endswith(install_subpath):
269 python_dirs.add(path[:len (install_subpath) * -1])
271 if path.endswith('.prs'):
272 presets.add(os.path.dirname(path))
273 elif path.endswith('.gep'):
274 encoding_targets.add(
275 os.path.abspath(os.path.join(os.path.dirname(path), '..')))
276 elif path.endswith('.pc'):
277 # Is there a -uninstalled pc file for this file?
278 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
279 if os.path.exists(uninstalled):
280 pkg_dirs.add(os.path.dirname(path))
282 if path.endswith('gstomx.conf'):
283 prepend_env_var(env, 'GST_OMX_CONFIG_DIR', os.path.dirname(path),
287 prepend_env_var(env, 'GST_PRESET_PATH', p, options.sysroot)
289 for t in encoding_targets:
290 prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t, options.sysroot)
292 for pkg_dir in pkg_dirs:
293 prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir, options.sysroot)
294 prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
300 for python_dir in python_dirs:
301 prepend_env_var(env, 'PYTHONPATH', python_dir, options.sysroot)
303 mesonpath = os.path.join(SCRIPTDIR, "meson")
304 if os.path.join(mesonpath):
305 # Add meson/ into PYTHONPATH if we are using a local meson
306 prepend_env_var(env, 'PYTHONPATH', mesonpath, options.sysroot)
309 if not 'XDG_DATA_DIRS' in env or not env['XDG_DATA_DIRS']:
310 # Preserve default paths when empty
311 prepend_env_var(env, 'XDG_DATA_DIRS', '/usr/local/share/:/usr/share/', '')
313 prepend_env_var (env, 'XDG_DATA_DIRS', os.path.join(options.builddir,
321 def get_windows_shell():
322 command = ['powershell.exe' ,'-noprofile', '-executionpolicy', 'bypass', '-file', 'cmd_or_ps.ps1']
323 result = subprocess.check_output(command)
324 return result.decode().strip()
326 if __name__ == "__main__":
327 parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
329 parser.add_argument("--builddir",
330 default=DEFAULT_BUILDDIR,
331 help="The meson build directory")
332 parser.add_argument("--srcdir",
334 help="The top level source directory")
335 parser.add_argument("--sysroot",
337 help="The sysroot path used during cross-compilation")
338 parser.add_argument("--wine",
340 help="Build a wine env based on specified wine command")
341 parser.add_argument("--winepath",
343 help="Exra path to set to WINEPATH.")
344 options, args = parser.parse_known_args()
346 if not os.path.exists(options.builddir):
347 print("GStreamer not built in %s\n\nBuild it and try again" %
350 options.builddir = os.path.abspath(options.builddir)
352 if not os.path.exists(options.srcdir):
353 print("The specified source dir does not exist" %
357 # The following incantation will retrieve the current branch name.
358 gst_version = git("rev-parse", "--symbolic-full-name", "--abbrev-ref", "HEAD",
359 repository_path=options.srcdir).strip('\n')
362 gst_version += '-' + os.path.basename(options.wine)
366 shell = get_windows_shell()
367 if shell == 'powershell.exe':
368 args = ['powershell.exe']
369 args += ['-NoLogo', '-NoExit']
370 prompt = 'function global:prompt { "[gst-' + gst_version + '"+"] PS " + $PWD + "> "}'
371 args += ['-Command', prompt]
373 args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
374 args += ['/k', 'prompt [gst-{}] $P$G'.format(gst_version)]
376 args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
377 if "bash" in args[0] and not strtobool(os.environ.get("GST_BUILD_DISABLE_PS1_OVERRIDE", r"FALSE")):
378 tmprc = tempfile.NamedTemporaryFile(mode='w')
379 bashrc = os.path.expanduser('~/.bashrc')
380 if os.path.exists(bashrc):
381 with open(bashrc, 'r') as src:
382 shutil.copyfileobj(src, tmprc)
383 tmprc.write('\nexport PS1="[gst-%s] $PS1"' % gst_version)
385 # Let the GC remove the tmp file
386 args.append("--rcfile")
387 args.append(tmprc.name)
388 if 'fish' in args[0]:
389 # Ignore SIGINT while using fish as the shell to make it behave
390 # like other shells such as bash and zsh.
391 # See: https://gitlab.freedesktop.org/gstreamer/gst-build/issues/18
392 signal.signal(signal.SIGINT, lambda x, y: True)
394 args.append('--init-command')
395 prompt_cmd = '''functions --copy fish_prompt original_fish_prompt
397 echo -n '[gst-{}] '(original_fish_prompt)
398 end'''.format(gst_version)
399 args.append(prompt_cmd)
401 exit(subprocess.call(args, close_fds=False,
402 env=get_subprocess_env(options, gst_version)))
403 except subprocess.CalledProcessError as e: