16 from distutils.sysconfig import get_python_lib
17 from distutils.util import strtobool
19 from scripts.common import get_meson
20 from scripts.common import git
21 from scripts.common import win32_get_short_path_name
22 from scripts.common import get_wine_shortpath
24 SCRIPTDIR = os.path.dirname(os.path.realpath(__file__))
25 PREFIX_DIR = os.path.join(SCRIPTDIR, 'prefix')
26 # Use '_build' as the builddir instead of 'build'
27 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, 'build')
28 if not os.path.exists(DEFAULT_BUILDDIR):
29 DEFAULT_BUILDDIR = os.path.join(SCRIPTDIR, '_build')
31 TYPELIB_REG = re.compile(r'.*\.typelib$')
32 SHAREDLIB_REG = re.compile(r'\.so|\.dylib|\.dll')
34 # libdir is expanded from option of the same name listed in the `meson
35 # introspect --buildoptions` output.
36 GSTPLUGIN_FILEPATH_REG_TEMPLATE = r'.*/{libdir}/gstreamer-1.0/[^/]+$'
37 GSTPLUGIN_FILEPATH_REG = None
40 if isinstance(o, str):
42 if isinstance(o, list):
44 raise AssertionError('Object {!r} must be a string or a list'.format(o))
47 if isinstance(o, str):
49 if isinstance(o, list):
52 raise AssertionError('Did not expect object {!r} to have more than one element'.format(o))
53 raise AssertionError('Object {!r} must be a string or a list'.format(o))
55 def prepend_env_var(env, var, value, sysroot):
56 if value.startswith(sysroot):
57 value = value[len(sysroot):]
58 # Try not to exceed maximum length limits for env vars on Windows
60 value = win32_get_short_path_name(value)
61 env_val = env.get(var, '')
62 val = os.pathsep + value + os.pathsep
63 # Don't add the same value twice
64 if val in env_val or env_val.startswith(value + os.pathsep):
66 env[var] = val + env_val
67 env[var] = env[var].replace(os.pathsep + os.pathsep, os.pathsep).strip(os.pathsep)
69 def is_library_target_and_not_plugin(target, filename):
71 Don't add plugins to PATH/LD_LIBRARY_PATH because:
73 2. It causes us to exceed the PATH length limit on Windows and Wine
75 if not target['type'].startswith('shared'):
77 if not target['installed']:
79 # Check if this output of that target is a shared library
80 if not SHAREDLIB_REG.search(filename):
82 # Check if it's installed to the gstreamer plugin location
83 for install_filename in listify(target['install_filename']):
84 if install_filename.endswith(os.path.basename(filename)):
87 # None of the installed files in the target correspond to the built
91 global GSTPLUGIN_FILEPATH_REG
92 if GSTPLUGIN_FILEPATH_REG is None:
93 GSTPLUGIN_FILEPATH_REG = re.compile(GSTPLUGIN_FILEPATH_REG_TEMPLATE)
94 if GSTPLUGIN_FILEPATH_REG.search(install_filename.replace('\\', '/')):
99 def get_wine_subprocess_env(options, env):
100 with open(os.path.join(options.builddir, 'meson-info', 'intro-buildoptions.json')) as f:
101 buildoptions = json.load(f)
103 prefix, = [o for o in buildoptions if o['name'] == 'prefix']
104 path = os.path.normpath(os.path.join(prefix['value'], 'bin'))
105 prepend_env_var(env, "PATH", path, options.sysroot)
106 wine_path = get_wine_shortpath(
107 options.wine.split(' '),
108 [path] + env.get('WINEPATH', '').split(';')
111 wine_path += ';' + options.winepath
112 env['WINEPATH'] = wine_path
113 env['WINEDEBUG'] = 'fixme-all'
118 def get_subprocess_env(options, gst_version):
119 env = os.environ.copy()
121 env["CURRENT_GST"] = os.path.normpath(SCRIPTDIR)
122 env["GST_VERSION"] = gst_version
123 env["GST_VALIDATE_SCENARIOS_PATH"] = os.path.normpath(
124 "%s/subprojects/gst-devtools/validate/data/scenarios" % SCRIPTDIR)
125 env["GST_VALIDATE_PLUGIN_PATH"] = os.path.normpath(
126 "%s/subprojects/gst-devtools/validate/plugins" % options.builddir)
127 env["GST_VALIDATE_APPS_DIR"] = os.path.normpath(
128 "%s/subprojects/gst-editing-services/tests/validate" % SCRIPTDIR)
129 env["GST_ENV"] = 'gst-' + gst_version
130 env["GST_REGISTRY"] = os.path.normpath(options.builddir + "/registry.dat")
131 prepend_env_var(env, "PATH", os.path.normpath(
132 "%s/subprojects/gst-devtools/validate/tools" % options.builddir),
136 return get_wine_subprocess_env(options, env)
138 prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'meson'),
141 env["GST_PLUGIN_SYSTEM_PATH"] = ""
142 env["GST_PLUGIN_SCANNER"] = os.path.normpath(
143 "%s/subprojects/gstreamer/libs/gst/helpers/gst-plugin-scanner" % options.builddir)
144 env["GST_PTP_HELPER"] = os.path.normpath(
145 "%s/subprojects/gstreamer/libs/gst/helpers/gst-ptp-helper" % options.builddir)
148 lib_path_envvar = 'PATH'
149 elif platform.system() == 'Darwin':
150 lib_path_envvar = 'DYLD_LIBRARY_PATH'
152 lib_path_envvar = 'LD_LIBRARY_PATH'
154 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(SCRIPTDIR, 'subprojects',
155 'gst-python', 'plugin'),
157 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(PREFIX_DIR, 'lib',
160 prepend_env_var(env, "GST_PLUGIN_PATH", os.path.join(options.builddir, 'subprojects',
163 prepend_env_var(env, "GST_VALIDATE_SCENARIOS_PATH",
164 os.path.join(PREFIX_DIR, 'share', 'gstreamer-1.0',
165 'validate', 'scenarios'),
167 prepend_env_var(env, "GI_TYPELIB_PATH", os.path.join(PREFIX_DIR, 'lib',
168 'lib', 'girepository-1.0'),
170 prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(PREFIX_DIR, 'lib', 'pkgconfig'),
174 prepend_env_var(env, "PATH", os.path.join(SCRIPTDIR, 'gstreamer', 'tools'),
177 # tools: gst-launch-1.0, gst-inspect-1.0
178 prepend_env_var(env, "PATH", os.path.join(options.builddir, 'subprojects',
179 'gstreamer', 'tools'),
181 prepend_env_var(env, "PATH", os.path.join(options.builddir, 'subprojects',
182 'gst-plugins-base', 'tools'),
185 # Library and binary search paths
186 prepend_env_var(env, "PATH", os.path.join(PREFIX_DIR, 'bin'),
188 if lib_path_envvar != 'PATH':
189 prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib'),
191 prepend_env_var(env, lib_path_envvar, os.path.join(PREFIX_DIR, 'lib64'),
193 elif 'QMAKE' in os.environ:
194 # There's no RPATH on Windows, so we need to set PATH for the qt5 DLLs
195 prepend_env_var(env, 'PATH', os.path.dirname(os.environ['QMAKE']),
199 targets_s = subprocess.check_output(meson + ['introspect', options.builddir, '--targets'])
200 targets = json.loads(targets_s.decode())
203 srcdir_path = pathlib.Path(options.srcdir)
205 build_options_s = subprocess.check_output(meson + ['introspect', options.builddir, '--buildoptions'])
206 build_options = json.loads(build_options_s.decode())
207 libdir, = [o['value'] for o in build_options if o['name'] == 'libdir']
208 libdir = libdir.replace('\\', '/')
210 global GSTPLUGIN_FILEPATH_REG_TEMPLATE
211 GSTPLUGIN_FILEPATH_REG_TEMPLATE = GSTPLUGIN_FILEPATH_REG_TEMPLATE.format(libdir=libdir)
213 for target in targets:
214 filenames = listify(target['filename'])
215 for filename in filenames:
216 root = os.path.dirname(filename)
217 if srcdir_path / "subprojects/gst-devtools/validate/plugins" in (srcdir_path / root).parents:
219 if filename.endswith('.dll'):
220 mono_paths.add(os.path.join(options.builddir, root))
221 if TYPELIB_REG.search(filename):
222 prepend_env_var(env, "GI_TYPELIB_PATH",
223 os.path.join(options.builddir, root),
225 elif is_library_target_and_not_plugin(target, filename):
226 prepend_env_var(env, lib_path_envvar,
227 os.path.join(options.builddir, root),
229 elif target['type'] == 'executable' and target['installed']:
230 paths.add(os.path.join(options.builddir, root))
232 with open(os.path.join(options.builddir, 'GstPluginsPath.json')) as f:
233 for plugin_path in json.load(f):
234 prepend_env_var(env, 'GST_PLUGIN_PATH', plugin_path,
238 prepend_env_var(env, 'PATH', p, options.sysroot)
242 prepend_env_var(env, "MONO_PATH", p, options.sysroot)
245 encoding_targets = set()
247 python_dirs = set(["%s/subprojects/gstreamer/libs/gst/helpers/" % options.srcdir])
248 if '--installed' in subprocess.check_output(meson + ['introspect', '-h']).decode():
249 installed_s = subprocess.check_output(meson + ['introspect', options.builddir, '--installed'])
250 for path, installpath in json.loads(installed_s.decode()).items():
251 installpath_parts = pathlib.Path(installpath).parts
252 path_parts = pathlib.Path(path).parts
254 # We want to add all python modules to the PYTHONPATH
255 # in a manner consistent with the way they would be imported:
256 # For example if the source path /home/meh/foo/bar.py
257 # is to be installed in /usr/lib/python/site-packages/foo/bar.py,
258 # we want to add /home/meh to the PYTHONPATH.
259 # This will only work for projects where the paths to be installed
260 # mirror the installed directory layout, for example if the path
261 # is /home/meh/baz/bar.py and the install path is
262 # /usr/lib/site-packages/foo/bar.py , we will not add anything
263 # to PYTHONPATH, but the current approach works with pygobject
264 # and gst-python at least.
265 if 'site-packages' in installpath_parts:
266 install_subpath = os.path.join(*installpath_parts[installpath_parts.index('site-packages') + 1:])
267 if path.endswith(install_subpath):
268 python_dirs.add(path[:len (install_subpath) * -1])
270 if path.endswith('.prs'):
271 presets.add(os.path.dirname(path))
272 elif path.endswith('.gep'):
273 encoding_targets.add(
274 os.path.abspath(os.path.join(os.path.dirname(path), '..')))
275 elif path.endswith('.pc'):
276 # Is there a -uninstalled pc file for this file?
277 uninstalled = "{0}-uninstalled.pc".format(path[:-3])
278 if os.path.exists(uninstalled):
279 pkg_dirs.add(os.path.dirname(path))
281 if path.endswith('gstomx.conf'):
282 prepend_env_var(env, 'GST_OMX_CONFIG_DIR', os.path.dirname(path),
286 prepend_env_var(env, 'GST_PRESET_PATH', p, options.sysroot)
288 for t in encoding_targets:
289 prepend_env_var(env, 'GST_ENCODING_TARGET_PATH', t, options.sysroot)
291 for pkg_dir in pkg_dirs:
292 prepend_env_var(env, "PKG_CONFIG_PATH", pkg_dir, options.sysroot)
293 prepend_env_var(env, "PKG_CONFIG_PATH", os.path.join(options.builddir,
299 for python_dir in python_dirs:
300 prepend_env_var(env, 'PYTHONPATH', python_dir, options.sysroot)
302 mesonpath = os.path.join(SCRIPTDIR, "meson")
303 if os.path.join(mesonpath):
304 # Add meson/ into PYTHONPATH if we are using a local meson
305 prepend_env_var(env, 'PYTHONPATH', mesonpath, options.sysroot)
308 if not 'XDG_DATA_DIRS' in env or not env['XDG_DATA_DIRS']:
309 # Preserve default paths when empty
310 prepend_env_var(env, 'XDG_DATA_DIRS', '/usr/local/share/:/usr/share/', '')
312 prepend_env_var (env, 'XDG_DATA_DIRS', os.path.join(options.builddir,
320 def get_windows_shell():
321 command = ['powershell.exe' ,'-noprofile', '-executionpolicy', 'bypass', '-file', 'cmd_or_ps.ps1']
322 result = subprocess.check_output(command)
323 return result.decode().strip()
325 if __name__ == "__main__":
326 parser = argparse.ArgumentParser(prog="gstreamer-uninstalled")
328 parser.add_argument("--builddir",
329 default=DEFAULT_BUILDDIR,
330 help="The meson build directory")
331 parser.add_argument("--srcdir",
333 help="The top level source directory")
334 parser.add_argument("--sysroot",
336 help="The sysroot path used during cross-compilation")
337 parser.add_argument("--wine",
339 help="Build a wine env based on specified wine command")
340 parser.add_argument("--winepath",
342 help="Exra path to set to WINEPATH.")
343 options, args = parser.parse_known_args()
345 if not os.path.exists(options.builddir):
346 print("GStreamer not built in %s\n\nBuild it and try again" %
349 options.builddir = os.path.abspath(options.builddir)
351 if not os.path.exists(options.srcdir):
352 print("The specified source dir does not exist" %
356 # The following incantation will retrieve the current branch name.
357 gst_version = git("rev-parse", "--symbolic-full-name", "--abbrev-ref", "HEAD",
358 repository_path=options.srcdir).strip('\n')
361 gst_version += '-' + os.path.basename(options.wine)
365 shell = get_windows_shell()
366 if shell == 'powershell.exe':
367 args = ['powershell.exe']
368 args += ['-NoLogo', '-NoExit']
369 prompt = 'function global:prompt { "[gst-' + gst_version + '"+"] PS " + $PWD + "> "}'
370 args += ['-Command', prompt]
372 args = [os.environ.get("COMSPEC", r"C:\WINDOWS\system32\cmd.exe")]
373 args += ['/k', 'prompt [gst-{}] $P$G'.format(gst_version)]
375 args = [os.environ.get("SHELL", os.path.realpath("/bin/sh"))]
376 if "bash" in args[0] and not strtobool(os.environ.get("GST_BUILD_DISABLE_PS1_OVERRIDE", r"FALSE")):
377 tmprc = tempfile.NamedTemporaryFile(mode='w')
378 bashrc = os.path.expanduser('~/.bashrc')
379 if os.path.exists(bashrc):
380 with open(bashrc, 'r') as src:
381 shutil.copyfileobj(src, tmprc)
382 tmprc.write('\nexport PS1="[gst-%s] $PS1"' % gst_version)
384 # Let the GC remove the tmp file
385 args.append("--rcfile")
386 args.append(tmprc.name)
388 exit(subprocess.call(args, close_fds=False,
389 env=get_subprocess_env(options, gst_version)))
390 except subprocess.CalledProcessError as e: