root/trunk/libffado/SConstruct

Revision 2736, 38.0 kB (checked in by jwoithe, 6 years ago)

Allow python interpreter to be specified at build time.

Patch from Nicolas Boulenguez (forwarded to ffado-devel by Benoit Delcour)
which allows packagers to directly specify the python interpreter which
should be used by FFADO components. This is useful for systems which do not
have /usr/bin/python due to only python 3 being installed.

Line 
1 # -*- coding: utf-8 -*-
2 #
3 # Copyright (C) 2007, 2008, 2010 Arnold Krille
4 # Copyright (C) 2007, 2008 Pieter Palmers
5 # Copyright (C) 2008, 2012 Jonathan Woithe
6 #
7 # This file is part of FFADO
8 # FFADO = Free Firewire (pro-)audio drivers for linux
9 #
10 # FFADO is based upon FreeBoB.
11 #
12 # This program is free software: you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation, either version 2 of the License, or
15 # (at your option) version 3 of the License.
16 #
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 # GNU General Public License for more details.
21 #
22 # You should have received a copy of the GNU General Public License
23 # along with this program.  If not, see <http://www.gnu.org/licenses/>.
24 #
25
26 FFADO_API_VERSION = "9"
27 FFADO_VERSION="2.4.9999"
28
29 from subprocess import Popen, PIPE
30 import os
31 import re
32 import sys
33 from string import Template
34 import imp
35 import distutils.sysconfig
36
37 if not os.path.isdir( "cache" ):
38         os.makedirs( "cache" )
39
40 opts = Variables( "cache/options.cache" )
41
42 opts.AddVariables(
43     BoolVariable( "DEBUG", """\
44 Build with \"-g -Wall\" rather than \"-O2\", and include extra debugging
45 checks in the code.""", True ),
46     BoolVariable( "DEBUG_MESSAGES", "Enable support for debug messages", True ),
47     BoolVariable( "PROFILE", "Build with symbols, warnings and other profiling info", False ),
48     PathVariable( "PREFIX", "The prefix where ffado will be installed to.", "/usr/local", PathVariable.PathAccept ),
49     PathVariable( "BINDIR", "Overwrite the directory where apps are installed to.", "$PREFIX/bin", PathVariable.PathAccept ),
50     PathVariable( "LIBDIR", "Overwrite the directory where libs are installed to.", "$PREFIX/lib", PathVariable.PathAccept ),
51     PathVariable( "INCLUDEDIR", "Overwrite the directory where headers are installed to.", "$PREFIX/include", PathVariable.PathAccept ),
52     PathVariable( "SHAREDIR", "Overwrite the directory where misc shared files are installed to.", "$PREFIX/share/libffado", PathVariable.PathAccept ),
53     PathVariable( "MANDIR", "Overwrite the directory where manpages are installed", "$PREFIX/man", PathVariable.PathAccept ),
54     PathVariable( "PYPKGDIR", "The directory where the python modules get installed.",
55         distutils.sysconfig.get_python_lib( prefix="$PREFIX" ), PathVariable.PathAccept ),
56     PathVariable( "UDEVDIR", "Overwrite the directory where udev rules are installed to.", "/lib/udev/rules.d/", PathVariable.PathAccept ),
57     BoolVariable( "ENABLE_BEBOB", "Enable/Disable support for the BeBoB platform.", True ),
58     BoolVariable( "ENABLE_FIREWORKS", "Enable/Disable support for the ECHO Audio FireWorks platform.", True ),
59     BoolVariable( "ENABLE_OXFORD", "Enable/Disable support for the Oxford Semiconductor FW platform.", True ),
60     BoolVariable( "ENABLE_MOTU", "Enable/Disable support for the MOTU platform.", True ),
61     BoolVariable( "ENABLE_DICE", "Enable/Disable support for the TCAT DICE platform.", True ),
62     BoolVariable( "ENABLE_METRIC_HALO", "Enable/Disable support for the Metric Halo platform.", False ),
63     BoolVariable( "ENABLE_RME", "Enable/Disable support for the RME platform.", True ),
64     BoolVariable( "ENABLE_DIGIDESIGN", "Enable/Disable support for Digidesign interfaces.", False ),
65     BoolVariable( "ENABLE_BOUNCE", "Enable/Disable the BOUNCE device.", False ),
66     BoolVariable( "ENABLE_GENERICAVC", """\
67 Enable/Disable the the generic avc part (mainly used by apple).
68   Note that disabling this option might be overwritten by other devices needing
69   this code.""", False ),
70     BoolVariable( "ENABLE_ALL", "Enable/Disable support for all devices.", False ),
71     BoolVariable( "SERIALIZE_USE_EXPAT", "Use libexpat for XML serialization.", False ),
72     EnumVariable( "BUILD_DOC", "Build API documentation", 'none', allowed_values=('all', 'user', 'none'), ignorecase=2),
73     EnumVariable( "BUILD_MIXER", "Build the ffado-mixer", 'auto', allowed_values=('auto', 'true', 'false'), ignorecase=2),
74     BoolVariable( "BUILD_TESTS", """\
75 Build the tests in their directory. As some contain quite some functionality,
76   this is on by default.
77   If you just want to use ffado with jack without the tools, you can disable this.\
78 """, True ),
79     BoolVariable( "BUILD_STATIC_TOOLS", "Build a statically linked version of the FFADO tools.", False ),
80     EnumVariable('DIST_TARGET', 'Build target for cross compiling packagers', 'auto', allowed_values=('auto', 'i386', 'i686', 'x86_64', 'powerpc', 'powerpc64', 'none' ), ignorecase=2),
81     BoolVariable( "ENABLE_OPTIMIZATIONS", "Enable optimizations and the use of processor specific extentions (MMX/SSE/...).", False ),
82     BoolVariable( "DETECT_USERSPACE_ENV", "Try to detect the user space environment and add necessary 32/64 bit machine flags.", True ),
83     BoolVariable( "PEDANTIC", "Enable -Werror and more pedantic options during compile.", False ),
84     BoolVariable( "CUSTOM_ENV", "Respect CC, CXX, CFLAGS, CXXFLAGS and LDFLAGS.\nOnly meant for distributors and gentoo-users who want to over-optimize their build.\n Using this is not supported by the ffado-devs!", False ),
85     ( "COMPILE_FLAGS", "Deprecated (use CFLAGS and CXXFLAGS with CUSTOM_ENV=True instead).  Add additional flags to the environment.\nOnly meant for distributors and gentoo-users who want to over-optimize their build.\n Using this is not supported by the ffado-devs!" ),
86     EnumVariable( "ENABLE_SETBUFFERSIZE_API_VER", "Report API version at runtime which includes support for dynamic buffer resizing (requires recent jack).", 'auto', allowed_values=('auto', 'true', 'false', 'force'), ignorecase=2),
87     ("PYTHON_INTERPRETER", "Python interpreter to be used by FFADO installation.", "/usr/bin/python"),
88
89     )
90
91 ## Load the builders in config
92 buildenv=os.environ
93
94 env = Environment( tools=['default','scanreplace','pyuic','pyuic4','pyuic5','dbus','doxygen','pkgconfig'], toolpath=['admin'], ENV = buildenv, options=opts )
95
96 custom_flags = False
97
98 if 'COMPILE_FLAGS' in env and len(env['COMPILE_FLAGS']) > 0:
99     print("The COMPILE_FLAGS option is deprecated. Use CFLAGS and CXXFLAGS with CUSTOM_ENV=True instead")
100     custom_flags = True
101     env.MergeFlags(env['COMPILE_FLAGS'])
102
103 if env['CUSTOM_ENV']:
104     custom_flags = True
105
106     # Honour the user choice of compiler (if any).
107     if 'CC' in os.environ and len(os.environ['CC']) > 0:
108         env['CC'] = os.environ['CC']
109     if 'CXX' in os.environ and len(os.environ['CXX']) > 0:
110         env['CXX'] = os.environ['CXX']
111
112     # Honour the user supplied flags (if any), but notify the user that this is not supported.
113     if 'CFLAGS' in os.environ and len(os.environ['CFLAGS']) > 0:
114         env.Append(CFLAGS = str(os.environ['CFLAGS'].replace('\"', '')))
115     if 'CXXFLAGS' in os.environ and len(os.environ['CXXFLAGS']) > 0:
116         env.Append(CXXFLAGS = str(os.environ['CXXFLAGS'].replace('\"', '')))
117     if 'LDFLAGS' in os.environ and len(os.environ['LDFLAGS']) > 0:
118         env.Append(LINKFLAGS = str(os.environ['LDFLAGS'].replace('\"', '')))
119
120 if custom_flags:
121     print('''
122  * Usage of additional flags is not supported by the ffado-devs.
123  * Use at own risk!
124  *
125  * Flags in use:
126  *   CC = %s
127  *   CXX = %s
128  *   CFLAGS = %s
129  *   CXXFLAGS = %s
130  *   LDFLAGS = %s
131 ''' % (env['CC'], env['CXX'], env['CFLAGS'], env['CXXFLAGS'], env['LINKFLAGS']))
132
133 Help( """
134 For building ffado you can set different options as listed below. You have to
135 specify them only once, scons will save the last value you used and re-use
136 that.
137 To really undo your settings and return to the factory defaults, remove the
138 "cache"-folder and the file ".sconsign.dblite" from this directory.
139 For example with: "rm -Rf .sconsign.dblite cache"
140
141 Note that this is a development version! Don't complain if its not working!
142 See www.ffado.org for stable releases.
143 """ )
144 Help( opts.GenerateHelpText( env ) )
145
146 # make sure the necessary dirs exist
147 if not os.path.isdir( "cache" ):
148         os.makedirs( "cache" )
149 if not os.path.isdir( 'cache/objects' ):
150     os.makedirs( 'cache/objects' )
151
152 CacheDir( 'cache/objects' )
153
154 opts.Save( 'cache/options.cache', env )
155
156 def ConfigGuess( context ):
157     context.Message( "Trying to find the system triple: " )
158     ret = os.popen( "/bin/sh admin/config.guess" ).read()[:-1]
159     context.Result( ret )
160     return ret
161
162 def CheckForApp( context, app ):
163     context.Message( "Checking whether '" + app + "' executes " )
164     ret = context.TryAction( app )
165     context.Result( ret[0] )
166     return ret[0]
167
168 def CheckForPyModule( context, module ):
169     context.Message( "Checking for the python module '" + module + "' " )
170     ret = context.TryAction( "$PYTHON_INTERPRETER $SOURCE", "import %s" % module, ".py" )
171     context.Result( ret[0] )
172     return ret[0]
173
174 def CompilerCheck( context ):
175     context.Message( "Checking for a working C-compiler " )
176     ret = context.TryRun( """
177 #include <stdio.h>
178
179 int main() {
180     printf( "Hello World!" );
181     return 0;
182 }""", '.c' )[0]
183     context.Result( ret )
184     if ret == 0:
185         return False;
186     context.Message( "Checking for a working C++-compiler " )
187     ret = context.TryRun( """
188 #include <iostream>
189
190 int main() {
191     std::cout << "Hello World!" << std::endl;
192     return 0;
193 }""", ".cpp" )[0]
194     context.Result( ret )
195     return ret
196
197 def CheckPKG(context, name):
198     context.Message( 'Checking for %s... ' % name )
199     ret = context.TryAction('pkg-config --exists \'%s\'' % name)[0]
200     context.Result( ret )
201     return ret
202
203 tests = {
204     "ConfigGuess" : ConfigGuess,
205     "CheckForApp" : CheckForApp,
206     "CheckForPyModule": CheckForPyModule,
207     "CompilerCheck" : CompilerCheck,
208     "CheckPKG" : CheckPKG,
209 }
210 tests.update( env['PKGCONFIG_TESTS'] )
211 tests.update( env['PYUIC_TESTS'] )
212 tests.update( env['PYUIC4_TESTS'] )
213
214 conf = Configure( env,
215     custom_tests = tests,
216     conf_dir = "cache/",
217     log_file = 'cache/config.log' )
218
219 version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)')
220
221 def VersionInt(vers):
222     match = version_re.match(vers)
223     if not match:
224         return -1
225     (maj, min, patch) = match.group(1, 2, 3)
226     # For now allow "min" to run up to 65535.  "maj" and "patch" are
227     # restricted to 0-255.
228     return (int(maj) << 24) | (int(min) << 8) | int(patch)
229
230 def CheckJackdVer():
231     # Suppress newline in python 2 and 3
232     sys.stdout.write('Checking jackd version...')
233     sys.stdout.flush()
234     ret = Popen("which jackd >/dev/null 2>&1 && jackd --version | tail -n 1 | cut -d ' ' -f 3", shell=True, stdout=PIPE).stdout.read()[:-1].decode()
235     if (ret == ""):
236         print("not installed")
237         return -1
238     else:
239         print(ret)
240     return VersionInt(ret)
241
242 if env['SERIALIZE_USE_EXPAT']:
243     env['SERIALIZE_USE_EXPAT']=1
244 else:
245     env['SERIALIZE_USE_EXPAT']=0
246
247 if env['ENABLE_BOUNCE'] or env['ENABLE_ALL']:
248     env['REQUIRE_LIBAVC']=1
249 else:
250     env['REQUIRE_LIBAVC']=0
251
252 if not env.GetOption('clean'):
253     #
254     # Check for working gcc and g++ compilers and their environment.
255     #
256     if not conf.CompilerCheck():
257         print("\nIt seems as if your system isn't even able to compile any C-/C++-programs. Probably you don't have gcc and g++ installed. Compiling a package from source without a working compiler is very hard to do, please install the needed packages.\nHint: on *ubuntu you need both gcc- and g++-packages installed, easiest solution is to install build-essential which depends on gcc and g++.")
258         Exit( 1 )
259
260     # Check for pkg-config before using pkg-config to check for other dependencies.
261     if not conf.CheckForPKGConfig():
262         print("\nThe program 'pkg-config' could not be found.\nEither you have to install the corresponding package first or make sure that PATH points to the right directions.")
263         Exit( 1 )
264
265     #
266     # The following checks are for headers and libs and packages we need.
267     #
268     allpresent = 1;
269     # for cache-serialization.
270     if env['SERIALIZE_USE_EXPAT']:
271         allpresent &= conf.CheckHeader( "expat.h" )
272         allpresent &= conf.CheckLib( 'expat', 'XML_ExpatVersion', '#include <expat.h>' )
273
274     pkgs = {
275         'libraw1394' : '2.0.5',
276         'libiec61883' : '1.1.0',
277         'libconfig++' : '0'
278         }
279
280     if env['REQUIRE_LIBAVC']:
281         pkgs['libavc1394'] = '0.5.3'
282
283     if not env['SERIALIZE_USE_EXPAT']:
284         if conf.CheckPKG('libxml++-3.0'):
285             pkgs['libxml++-3.0'] = '3.0.0'
286         if not('libxml++-3.0' in pkgs):
287             pkgs['libxml++-2.6'] = '2.13.0'
288
289     # Provide a way for users to compile newer libffado which will work
290     # against older jack installations which will not accept the new API
291     # version reported at runtime.
292     have_jack = conf.CheckPKG('jack')
293     if have_jack:
294         good_jack1 = conf.CheckPKG('jack < 1.9.0') and conf.CheckPKG('jack >= 0.121.4')
295         good_jack2 = conf.CheckPKG('jack >= 1.9.9')
296     else:
297         jackd_ver = CheckJackdVer()
298         if (jackd_ver != -1):
299             # If jackd is unknown to pkg-config but is never-the-less
300             # runnable, use the version number reported by it.  This means
301             # users don't have to have jack development files present on
302             # their system for this to work.
303             have_jack = (jackd_ver >= VersionInt('0.0.0'))
304             good_jack1 = (jackd_ver < VersionInt('1.9.0')) and (jackd_ver >= VersionInt('0.121.4'))
305             good_jack2 = (jackd_ver >= VersionInt('1.9.9'))
306
307     if env['ENABLE_SETBUFFERSIZE_API_VER'] == 'auto':
308         if not(have_jack):
309             print("""
310 No Jack Audio Connection Kit (JACK) installed: assuming a FFADO
311 setbuffersize-compatible version will be used.
312 """)
313         elif not(good_jack1 or good_jack2):
314             FFADO_API_VERSION="8"
315             print("""
316 Installed Jack Audio Connection Kit (JACK) jack does not support FFADO
317 setbuffersize API: will report earlier API version at runtime.  Consider
318 upgrading to jack1 >=0.122.0 or jack2 >=1.9.9 at some point, and then
319 recompile ffado to gain access to this added feature.
320 """)
321         else:
322             print("Installed Jack Audio Connection Kit (JACK) supports FFADO setbuffersize API")
323     elif env['ENABLE_SETBUFFERSIZE_API_VER'] == 'true':
324         if (have_jack and not(good_jack1) and not(good_jack2)):
325             print("""
326 SetBufferSize API version is enabled but no suitable version of Jack Audio
327 Connection Kit (JACK) has been found.  The resulting FFADO would cause your
328 jackd to abort with "incompatible FFADO version".  Please upgrade to
329 jack1 >=0.122.0 or jack2 >=1.9.9, or set ENABLE_SETBUFFERSIZE_API_VER to "auto"
330 or "false".
331 """)
332             # Although it's not strictly an error, in almost every case that
333             # this occurs the user will want to know about it and fix the
334             # problem, so we exit so they're guaranteed of seeing the above
335             # message.
336             Exit( 1 )
337         else:
338             print("Will report SetBufferSize API version at runtime")
339     elif env['ENABLE_SETBUFFERSIZE_API_VER'] == 'force':
340         print("Will report SetBufferSize API version at runtime")
341     else:
342         FFADO_API_VERSION="8"
343         print("Will not report SetBufferSize API version at runtime")
344
345     for pkg in pkgs:
346         name2 = pkg.replace("+","").replace(".","").replace("-","").upper()
347         env['%s_FLAGS' % name2] = conf.GetPKGFlags( pkg, pkgs[pkg] )
348         #print('%s_FLAGS' % name2)
349         if env['%s_FLAGS'%name2] == 0:
350             allpresent &= 0
351
352     if not allpresent:
353         print("""
354 (At least) One of the dependencies is missing. I can't go on without it, please
355 install the needed packages for each of the lines saying "no".
356 (Remember to also install the *-devel packages!)
357
358 And remember to remove the cache with "rm -Rf .sconsign.dblite cache" so the
359 results above get rechecked.
360 """)
361         Exit( 1 )
362
363     # libxml++-2.6 requires a c++11 compiler as of version 2.39.1.  The
364     # gnu++11 standard seems to work both with these later libxml++ versions
365     # and ffado itself, although a significant number of warnings are
366     # produced.  Add the necessary option to CXXFLAGS if required.
367     if conf.CheckPKG('libxml++-2.6 >= 2.39.1'):
368         env.Append(CXXFLAGS = '-std=gnu++11')
369     if conf.CheckPKG('libxml++-3.0 >= 3.0.0'):
370         env.Append(CXXFLAGS = '-std=gnu++11')
371
372     # Check for C99 lrint() and lrintf() functions used to convert from
373     # float to integer more efficiently via float_cast.h.  If not
374     # present the standard slower methods will be used instead.  This
375     # might not be the best way of testing for these but it's the only
376     # way which seems to work properly.  CheckFunc() fails due to
377     # argument count problems.
378     if 'CFLAGS' in env:
379         oldcf = env['CFLAGS']
380     else:
381         oldcf = ""
382     env.Append(CFLAGS = '-std=c99')
383     if conf.CheckLibWithHeader( "m", "math.h", "c", "lrint(3.2);" ):
384         HAVE_LRINT = 1
385     else:
386         HAVE_LRINT = 0
387     if conf.CheckLibWithHeader( "m", "math.h", "c", "lrintf(3.2);" ):
388         HAVE_LRINTF = 1
389     else:
390         HAVE_LRINTF = 0
391     env['HAVE_LRINT'] = HAVE_LRINT;
392     env['HAVE_LRINTF'] = HAVE_LRINTF;
393     env.Replace(CFLAGS=oldcf)
394
395 #
396 # Optional checks follow:
397 #
398
399 # PyQT checks
400 if env['BUILD_MIXER'] != 'false':
401     have_dbus = ((conf.CheckForApp( 'which pyuic4' ) and conf.CheckForPyModule( 'dbus.mainloop.qt' )) or (conf.CheckForApp( 'which pyuic5' ) and conf.CheckForPyModule( 'dbus.mainloop.pyqt5' )))
402     have_pyqt4 = (conf.CheckForApp( 'which pyuic4' ) and conf.CheckForPyModule( 'PyQt4' ))
403     have_pyqt5 = (conf.CheckForApp( 'which pyuic5' ) and conf.CheckForPyModule( 'PyQt5' ))
404     if ((have_pyqt4 or have_pyqt5) and have_dbus):
405         env['BUILD_MIXER'] = 'true'
406     elif not env.GetOption('clean'):
407         if env['BUILD_MIXER'] == 'auto':
408             env['BUILD_MIXER'] = 'false'
409             print("""
410 The prerequisites ('pyuic4'/'pyuic5' and the python-modules 'dbus' and
411 'PyQt4'/'PyQt5', the packages could be named like dbus-python and PyQt) to
412 build the mixer were not found. Therefore the qt mixer will not be installed.""")
413         else: # env['BUILD_MIXER'] == 'true'
414             print("""
415 The prerequisites ('pyuic4'/'pyuic5' and the python-modules 'dbus' and
416 'PyQt4'/'PyQt5', the packages could be named like dbus-python and PyQt) to
417 build the mixer were not found, but BUILD_MIXER was requested.""")
418             Exit( 1 )
419
420 env['XDG_TOOLS'] = False
421 if env['BUILD_MIXER'] == 'true':
422     if conf.CheckForApp( 'xdg-desktop-menu --help' ) and conf.CheckForApp( 'xdg-icon-resource --help' ):
423         env['XDG_TOOLS'] = True
424     else:
425         print("""
426 I couldn't find the 'xdg-desktop-menu' and 'xdg-icon-resource' programs. These
427 are needed to add the fancy entry for the mixer to your menu, but you can still
428 start it by executing "ffado-mixer".""")
429
430 #
431 # Optional pkg-config
432 #
433 pkgs = {
434     'alsa': '0',
435     'dbus-1': '1.0',
436     'dbus-c++-1' : '0',
437     }
438 for pkg in pkgs:
439     name2 = pkg.replace("+","").replace(".","").replace("-","").upper()
440     env['%s_FLAGS' % name2] = conf.GetPKGFlags( pkg, pkgs[pkg] )
441
442 if not env['DBUS1_FLAGS'] or not env['DBUSC1_FLAGS'] or not conf.CheckForApp('which dbusxx-xml2cpp'):
443     env['DBUS1_FLAGS'] = b""
444     env['DBUSC1_FLAGS'] = b""
445     print("""
446 One of the dbus-headers, the dbus-c++-headers and/or the application
447 'dbusxx-xml2cpp' where not found. The dbus-server for ffado will therefore not
448 be built.
449 """)
450 else:
451     # Get the directory where dbus stores the service-files
452     env['dbus_service_dir'] = conf.GetPKGVariable( 'dbus-1', 'session_bus_services_dir' ).strip()
453     # this is required to indicate that the DBUS version we use has support
454     # for platform dependent threading init functions
455     # this is true for DBUS >= 0.96 or so. Since we require >= 1.0 it is
456     # always true
457     env['DBUS1_FLAGS'] += b" -DDBUS_HAS_THREADS_INIT_DEFAULT"
458
459     # The controlserver-glue.h file generated by dbusxx-xml2cpp generates
460     # a large number of instances where call.reader()'s return value is
461     # stored (in ri) but not used.  This generates a compiler warning which
462     # we can do nothing about.  Therefore when compiling dbus-related
463     # code, suppress the "set but not used" warning.
464     env['DBUS1_FLAGS'] += b" -Wno-unused-but-set-variable"
465
466 config_guess = conf.ConfigGuess()
467
468 env = conf.Finish()
469
470 if env['DEBUG']:
471     print("Doing a debug build")
472     env.MergeFlags( "-Wall -g -DDEBUG" )
473     env['DEBUG_MESSAGES'] = True
474 elif not custom_flags:
475     # Only merge -O2 to flags if the user has not specified custom flags.
476     env.MergeFlags( "-O2" )
477
478 if env['DEBUG_MESSAGES']:
479     env.MergeFlags( "-DDEBUG_MESSAGES" )
480
481 if env['PROFILE']:
482     print("Doing a PROFILE build")
483     env.MergeFlags( "-Wall -g" )
484
485 if env['PEDANTIC']:
486     env.MergeFlags( "-Werror" )
487
488
489 if env['ENABLE_ALL']:
490     env['ENABLE_BEBOB'] = True
491     env['ENABLE_FIREWORKS'] = True
492     env['ENABLE_OXFORD'] = True
493     env['ENABLE_MOTU'] = True
494     env['ENABLE_DICE'] = True
495     env['ENABLE_METRIC_HALO'] = True
496     env['ENABLE_RME'] = True
497     env['ENABLE_DIGIDESIGN'] = True
498     env['ENABLE_BOUNCE'] = True
499
500
501 env['BUILD_STATIC_LIB'] = False
502 if env['BUILD_STATIC_TOOLS']:
503     print("Building static versions of the tools...")
504     env['BUILD_STATIC_LIB'] = True
505
506 env['build_base']="#/"
507
508 #
509 # Get the DESTDIR (if wanted) from the commandline
510 #
511 env.destdir = ARGUMENTS.get( 'DESTDIR', "" )
512
513 #
514 # Uppercase variables are for usage in code, lowercase versions for usage in
515 # scons-files for installing.
516 #
517 env['BINDIR'] = Template( env['BINDIR'] ).safe_substitute( env )
518 env['LIBDIR'] = Template( env['LIBDIR'] ).safe_substitute( env )
519 env['INCLUDEDIR'] = Template( env['INCLUDEDIR'] ).safe_substitute( env )
520 env['SHAREDIR'] = Template( env['SHAREDIR'] ).safe_substitute( env )
521 env['UDEVDIR'] = Template( env['UDEVDIR'] ).safe_substitute( env )
522 env['PYTHON_INTERPRETER'] = Template( env['PYTHON_INTERPRETER'] ).safe_substitute( env )
523 env['prefix'] = Template( env.destdir + env['PREFIX'] ).safe_substitute( env )
524 env['bindir'] = Template( env.destdir + env['BINDIR'] ).safe_substitute( env )
525 env['libdir'] = Template( env.destdir + env['LIBDIR'] ).safe_substitute( env )
526 env['includedir'] = Template( env.destdir + env['INCLUDEDIR'] ).safe_substitute( env )
527 env['sharedir'] = Template( env.destdir + env['SHAREDIR'] ).safe_substitute( env )
528 env['mandir'] = Template( env.destdir + env['MANDIR'] ).safe_substitute( env )
529 env['pypkgdir'] = Template( env.destdir + env['PYPKGDIR'] ).safe_substitute( env )
530 env['udevdir'] = Template( env.destdir + env['UDEVDIR'] ).safe_substitute( env )
531 env['PYPKGDIR'] = Template( env['PYPKGDIR'] ).safe_substitute( env )
532
533 env.Command( target=env['sharedir'], source="", action=Mkdir( env['sharedir'] ) )
534
535 env.Alias( "install", env['libdir'] )
536 env.Alias( "install", env['includedir'] )
537 env.Alias( "install", env['sharedir'] )
538 env.Alias( "install", env['bindir'] )
539 env.Alias( "install", env['mandir'] )
540 if env['BUILD_MIXER'] == 'true':
541     env.Alias( "install", env['pypkgdir'] )
542
543 #
544 # shamelessly copied from the Ardour scons file
545 #
546
547 opt_flags = []
548 env['USE_SSE'] = 0
549
550 # guess at the platform, used to define compiler flags
551
552 config_cpu = 0
553 config_arch = 1
554 config_kernel = 2
555 config_os = 3
556 config = config_guess.split ("-")
557
558 needs_fPIC = False
559
560 #=== Begin Revised CXXFLAGS =========================================
561 def outputof(*cmd):
562     """Run a command without running a shell, return cmd's stdout
563     """
564     p = Popen(cmd, stdout=PIPE)
565     return p.communicate()[0]
566
567 def cpuinfo_kv():
568     """generator which reads lines from Linux /proc/cpuinfo and splits them
569     into key:value tokens and yields (key, value) tuple.
570     """
571     f = open('/proc/cpuinfo', 'r')
572     for line in f:
573         line = line.strip()
574         if line:
575             k,v = line.split(':', 1)
576             yield (k.strip(), v.strip())
577     f.close()
578
579
580 class CpuInfo (object):
581     """Collects information about the CPU, mainly from /proc/cpuinfo
582     """
583     def __init__(self):
584         self.sysname, self.hostname, self.release, self.version, self.machine = os.uname()
585         # general CPU architecture
586         self.is_x86 = self.machine in ('i686', 'x86_64') or \
587                       re.match("i[3-5]86", self.machine) or False
588         self.is_powerpc = self.machine in ('ppc64', 'ppc', 'powerpc', 'powerpc64', 'ppc64le')
589         #!!! probably not comprehensive
590         self.is_mips = self.machine == 'mips'
591         #!!! not a comprehensive list. uname -m on one android phone reports 'armv71'
592         # I have no other arm devices I can check
593         self.is_arm = self.machine in ('armv71', )
594
595         self.cpu_count = 0
596         if self.is_x86:
597             self.cpu_info_x86()
598         elif self.is_powerpc:
599             self.cpu_info_ppc()
600         elif self.is_mips:
601             self.cpu_info_mips()
602
603         # 64-bit (x86_64/AMD64/Intel64)
604         # Long Mode (x86-64: amd64, also known as Intel 64, i.e. 64-bit capable)
605         self.is_64bit = (self.is_x86 and 'lm' in self.x86_flags) or \
606                         (self.is_powerpc and \
607                             ('970' in self.ppc_type or 'power8' in self.ppc_type.lower()))
608
609         # Hardware virtualization capable: vmx (Intel), svm (AMD)
610         self.has_hwvirt = self.is_x86 and (
611                             (self.is_amd and 'svm' in self.x86_flags) or
612                             (self.is_intel and 'vmx' in self.x86_flags))
613
614         # Physical Address Extensions (support for more than 4GB of RAM)
615         self.has_pae = self.is_x86 and 'pae' in self.x86_flags
616
617
618     def cpu_info_x86(self):
619         "parse /proc/cpuinfo for x86 kernels"
620         for k,v in cpuinfo_kv():
621             if k == 'processor':
622                 self.cpu_count += 1
623                 if self.cpu_count > 1:
624                     # assume all CPUs are identical features, no need to
625                     # parse all of them
626                     continue
627             elif k == 'vendor_id': # AuthenticAMD, GenuineIntel
628                 self.vendor_id = v
629                 self.is_amd = v == 'AuthenticAMD'
630                 self.is_intel = v == 'GenuineIntel'
631             elif k == 'flags':
632                 self.x86_flags = v.split()
633             elif k == 'model name':
634                 self.model_name = v
635             elif k == 'cpu family':
636                 self.cpu_family = v
637             elif k == 'model':
638                 self.model = v
639
640     def cpu_info_ppc(self):
641         "parse /proc/cpuinfo for PowerPC kernels"
642         # http://en.wikipedia.org/wiki/List_of_PowerPC_processors
643         # PowerPC 7xx family
644         # PowerPC 740 and 750, 233-366 MHz
645         # 745/755, 300–466 MHz
646
647         # PowerPC G4 series
648         # 7400/7410 350 - 550 MHz, uses AltiVec, a SIMD extension of the original PPC specs
649         # 7450 micro-architecture family up to 1.5 GHz and 256 kB on-chip L2 cache and improved Altivec
650         # 7447/7457 micro-architecture family up to 1.8 GHz with 512 kB on-chip L2 cache
651         # 7448 micro-architecture family (1.5 GHz) in 90 nm with 1MB L2 cache and slightly
652         #  improved AltiVec (out of order instructions).
653         # 8640/8641/8640D/8641D with one or two e600 (Formerly known as G4) cores, 1MB L2 cache
654
655         # PowerPC G5 series
656         # 970 (2003), 64-bit, derived from POWER4, enhanced with VMX, 512 kB L2 cache, 1.4 – 2 GHz
657         # 970FX (2004), manufactured at 90 nm, 1.8 - 2.7 GHz
658         # 970GX (2006), manufactured at 90 nm, 1MB L2 cache/core, 1.2 - 2.5 GHz
659         # 970MP (2005), dual core, 1 MB L2 cache/core, 1.6 - 2.5 GHz
660         for k,v in cpuinfo_kv():
661             if k == 'processor':
662                 self.cpu_count += 1
663             elif k == 'cpu':
664                 self.is_altivec_supported = 'altivec' in v
665                 if ',' in v:
666                     ppc_type, x = v.split(',')
667                 else:
668                     ppc_type = v
669                 self.ppc_type = ppc_type.strip()
670         # older kernels might not have a 'processor' line
671         if self.cpu_count == 0:
672             self.cpu_count += 1
673
674
675     def cpu_info_mips(self):
676         "parse /proc/cpuinfo for MIPS kernels"
677         for k,v in cpuinfo_kv():
678             if k == 'processor':
679                 self.cpu_count += 1
680             elif k == 'cpu model':
681                 self.mips_cpu_model = v
682
683
684 def is_userspace_32bit(cpuinfo):
685     """Even if `uname -m` reports a 64-bit architecture, userspace could still
686     be 32-bit, such as Debian on powerpc64. This function tries to figure out
687     if userspace is 32-bit, i.e. we might need to pass '-m32' or '-m64' to gcc.
688     """
689     if not cpuinfo.is_64bit:
690         return True
691     # note that having a 64-bit CPU means nothing for these purposes. You could
692     # run a completely 32-bit system on a 64-bit capable CPU.
693     answer = None
694
695     # If setting DIST_TARGET to i686 on a 64-bit CPU to facilitate
696     # compilation of a multilib environment, force 32-bit.
697     if env['DIST_TARGET'] == 'i686':
698         return True
699
700     # Debian ppc64 returns machine 'ppc64', but userspace might be 32-bit
701     # We'll make an educated guess by examining a known executable
702     exe = '/bin/mount'
703     if os.path.isfile(exe):
704         #print('Found %s' % exe)
705         if os.path.islink(exe):
706             real_exe = os.path.join(os.path.dirname(exe), os.readlink(exe))
707             #print('%s is a symlink to %s' % (exe, real_exe))
708         else:
709             real_exe = exe
710         # presumably if a person is running this script, they should have
711         # a gcc toolchain installed...
712         x = outputof('objdump', '-Wi', real_exe)
713         # should emit a line that looks like this:
714         # /bin/mount:     file format elf32-i386
715         # or like this:
716         # /bin/mount:     file format elf64-x86-64
717         # or like this:
718         # /bin/mount:     file format elf32-powerpc
719         for line in x.split(b'\n'):
720             line = line.strip().decode()
721             if line.startswith(real_exe):
722                 x, fmt = line.rsplit(None, 1)
723                 answer = 'elf32' in fmt
724                 break
725     else:
726         print('!!! Not found %s' % exe)
727     return answer
728
729
730 def cc_flags_x86(cpuinfo, enable_optimizations):
731     """add certain gcc -m flags based on CPU features
732     """
733     # See http://gcc.gnu.org/onlinedocs/gcc-4.4.4/gcc/i386-and-x86_002d64-Options.html
734     cc_opts = []
735     if cpuinfo.machine == 'i586':
736         cc_opts.append('-march=i586')
737     elif cpuinfo.machine == 'i686':
738         cc_opts.append('-march=i686')
739
740     if 'mmx' in cpuinfo.x86_flags:
741         cc_opts.append('-mmmx')
742
743     # map from proc/cpuinfo flags to gcc options
744     opt_flags = [
745             ('sse', ('-mfpmath=sse', '-msse')),
746             ('sse2', '-msse2'),
747             ('ssse3', '-mssse3'),
748             ('sse4', '-msse4'),
749             ('sse4_1', '-msse4.1'),
750             ('sse4_2', '-msse4.2'),
751             ('sse4a', '-msse4a'),
752             ('3dnow', '-m3dnow'),
753     ]
754     if enable_optimizations:
755         for flag, gccopt in opt_flags:
756             if flag in cpuinfo.x86_flags:
757                 if isinstance(gccopt, (tuple, list)):
758                     cc_opts.extend(gccopt)
759                 else:
760                     cc_opts.append(gccopt)
761     return cc_opts
762
763
764 def cc_flags_powerpc(cpuinfo, enable_optimizations):
765     """add certain gcc -m flags based on CPU model
766     """
767     cc_opts = []
768     if cpuinfo.is_altivec_supported:
769         cc_opts.append ('-maltivec')
770         cc_opts.append ('-mabi=altivec')
771
772     if re.match('74[0145][0578]A?', cpuinfo.ppc_type) is not None:
773         cc_opts.append ('-mcpu=7400')
774         cc_opts.append ('-mtune=7400')
775     elif re.match('750', cpuinfo.ppc_type) is not None:
776         cc_opts.append ('-mcpu=750')
777         cc_opts.append ('-mtune=750')
778     elif re.match('PPC970', cpuinfo.ppc_type) is not None:
779         cc_opts.append ('-mcpu=970')
780         cc_opts.append ('-mtune=970')
781     elif re.match('Cell Broadband Engine', cpuinfo.ppc_type) is not None:
782         cc_opts.append('-mcpu=cell')
783         cc_opts.append('-mtune=cell')
784     return cc_opts
785 #=== End Revised CXXFLAGS =========================================
786
787 # Autodetect
788 if env['DIST_TARGET'] == 'auto':
789     if re.search ("x86_64", config[config_cpu]) is not None:
790         env['DIST_TARGET'] = 'x86_64'
791     elif re.search("i[0-5]86", config[config_cpu]) is not None:
792         env['DIST_TARGET'] = 'i386'
793     elif re.search("i686", config[config_cpu]) is not None:
794         env['DIST_TARGET'] = 'i686'
795     elif re.search("powerpc64", config[config_cpu]) is not None:
796         env['DIST_TARGET'] = 'powerpc64'
797     elif re.search("powerpc", config[config_cpu]) is not None:
798         env['DIST_TARGET'] = 'powerpc'
799     else:
800         env['DIST_TARGET'] = config[config_cpu]
801     print("Detected DIST_TARGET = " + env['DIST_TARGET'])
802
803 #=== Begin Revised CXXFLAGS =========================================
804 # comment on DIST_TARGET up top implies it can be used for cross-compiling
805 # but that's not true because even if it is not 'auto' the original
806 # script still reads /proc/cpuinfo to determine gcc arch flags.
807 # This script does the same as the original. Needs to be fixed someday.
808 cpuinfo = CpuInfo()
809 if cpuinfo.is_x86:
810     opt_flags.extend(cc_flags_x86(cpuinfo, env['ENABLE_OPTIMIZATIONS']))
811 if cpuinfo.is_powerpc:
812     opt_flags.extend(cc_flags_powerpc(cpuinfo, env['ENABLE_OPTIMIZATIONS']))
813 if '-msse' in opt_flags:
814     env['USE_SSE'] = 1
815 if '-msse2' in opt_flags:
816     env['USE_SSE2'] = 1
817
818 if env['DETECT_USERSPACE_ENV']:
819     m32 = is_userspace_32bit(cpuinfo)
820     print('User space is %s' % (m32 and '32-bit' or '64-bit'))
821     if cpuinfo.is_powerpc:
822         if m32:
823             print("Doing a 32-bit PowerPC build for %s CPU" % cpuinfo.ppc_type)
824             machineflags = { 'CXXFLAGS' : ['-m32'] }
825         else:
826             print("Doing a 64-bit PowerPC build for %s CPU" % cpuinfo.ppc_type)
827             machineflags = { 'CXXFLAGS' : ['-m64'] }
828         env.MergeFlags( machineflags )
829     elif cpuinfo.is_x86:
830         if m32:
831             print("Doing a 32-bit %s build for %s" % (cpuinfo.machine, cpuinfo.model_name))
832             if cpuinfo.machine == 'x86_64':
833                 machineflags = { 'CXXFLAGS' : ['-mx32'] }
834             else:
835                 machineflags = { 'CXXFLAGS' : ['-m32'] }
836         else:
837             print("Doing a 64-bit %s build for %s" % (cpuinfo.machine, cpuinfo.model_name))
838             machineflags = { 'CXXFLAGS' : ['-m64'] }
839             needs_fPIC = True
840         env.MergeFlags( machineflags )
841 #=== End Revised CXXFLAGS =========================================
842
843
844 if needs_fPIC or ( 'COMPILE_FLAGS' in env and '-fPIC' in env['COMPILE_FLAGS'] ):
845     env.MergeFlags( "-fPIC" )
846
847 # end of processor-specific section
848 if env['ENABLE_OPTIMIZATIONS']:
849     opt_flags.extend (["-fomit-frame-pointer","-ffast-math","-funroll-loops"])
850     env.MergeFlags( opt_flags )
851     print("Doing an optimized build...")
852
853 env['REVISION'] = os.popen('svnversion .').read()[:-1]
854 # This may be as simple as '89' or as complex as '4123:4184M'.
855 # We'll just use the last bit.
856 env['REVISION'] = env['REVISION'].split(':')[-1]
857
858 # try to circumvent localized versions
859 if len(env['REVISION']) >= 5 and env['REVISION'][0:6] == 'export':
860     env['REVISION'] = ''
861
862 # avoid the 1.999.41- type of version for exported versions
863 if env['REVISION'] != '':
864         env['REVISIONSTRING'] = '-' + env['REVISION']
865 else:
866         env['REVISIONSTRING'] = ''
867
868 env['FFADO_API_VERSION'] = FFADO_API_VERSION
869
870 env['PACKAGE'] = "libffado"
871 env['VERSION'] = FFADO_VERSION
872 env['LIBVERSION'] = "1.0.0"
873
874 env['CONFIGDIR'] = "~/.ffado"
875 env['CACHEDIR'] = "~/.ffado"
876
877 env['USER_CONFIG_FILE'] = env['CONFIGDIR'] + "/configuration"
878 env['SYSTEM_CONFIG_FILE'] = env['SHAREDIR'] + "/configuration"
879
880 env['REGISTRATION_URL'] = "http://ffado.org/deviceregistration/register.php?action=register"
881
882 #
883 # To have the top_srcdir as the doxygen-script is used from auto*
884 #
885 env['top_srcdir'] = env.Dir( "." ).abspath
886
887 #
888 # Start building
889 #
890 env.ScanReplace( "config.h.in" )
891 env.ScanReplace( "config_debug.h.in" )
892 env.ScanReplace( "version.h.in" )
893
894 # ensure that the config.h is updated
895 env.Depends( "config.h", "SConstruct" )
896 env.Depends( "config.h", 'cache/options.cache' )
897
898 # update version.h whenever the version or SVN revision changes
899 env.Depends( "version.h", env.Value(env['REVISION']))
900 env.Depends( "version.h", env.Value(env['VERSION']))
901
902 env.Depends( "libffado.pc", "SConstruct" )
903 pkgconfig = env.ScanReplace( "libffado.pc.in" )
904 env.Install( env['libdir'] + '/pkgconfig', pkgconfig )
905
906 env.Install( env['sharedir'], 'configuration' )
907
908 subdirs=['src','libffado','support','doc']
909 if env['BUILD_TESTS']:
910     subdirs.append('tests')
911
912 env.SConscript( dirs=subdirs, exports="env" )
913
914 if 'debian' in COMMAND_LINE_TARGETS:
915     env.SConscript("deb/SConscript", exports="env")
916
917 # By default only src is built but all is cleaned
918 if not env.GetOption('clean'):
919     Default( 'src' )
920     Default( 'support' )
921     if env['BUILD_TESTS']:
922         Default( 'tests' )
923     if env['BUILD_DOC'] != 'none':
924         Default( 'doc' )
925
926 #
927 # Deal with the DESTDIR vs. xdg-tools conflict (which is basicely that the
928 # xdg-tools can't deal with DESTDIR, so the packagers have to deal with this
929 # their own :-/
930 #
931 if len(env.destdir) > 0:
932     if not len( ARGUMENTS.get( "WILL_DEAL_WITH_XDG_MYSELF", "" ) ) > 0:
933         print("""
934 WARNING!
935 You are using the (packagers) option DESTDIR to install this package to a
936 different place than the real prefix. As the xdg-tools can't cope with
937 that, the .desktop-files are not installed by this build, you have to
938 deal with them your own.
939 (And you have to look into the SConstruct to learn how to disable this
940 message.)
941 """)
942 else:
943
944     def CleanAction( action ):
945         if env.GetOption( "clean" ):
946             env.Execute( action )
947
948     if env['BUILD_MIXER'] == 'true' and env['XDG_TOOLS']:
949         if not env.GetOption("clean"):
950             action = "install"
951         else:
952             action = "uninstall"
953         mixerdesktopaction = env.Action( "-xdg-desktop-menu %s support/xdg/ffado.org-ffadomixer.desktop" % action )
954         mixericonaction = env.Action( "-xdg-icon-resource %s --size 64 --novendor --context apps support/xdg/hi64-apps-ffado.png ffado" % action )
955         env.Command( "__xdgstuff1", None, mixerdesktopaction )
956         env.Command( "__xdgstuff2", None, mixericonaction )
957         env.Alias( "install", ["__xdgstuff1", "__xdgstuff2" ] )
958         CleanAction( mixerdesktopaction )
959         CleanAction( mixericonaction )
960
961 #
962 # Create a tags-file for easier emacs/vim-source-browsing
963 #  I don't know if the dependency is right...
964 #
965 findcommand = "find . \( -path \"*.h\" -o -path \"*.cpp\" -o -path \"*.c\" \) \! -path \"*.svn*\" \! -path \"./doc*\" \! -path \"./cache*\""
966 env.Command( "tags", "", findcommand + " |xargs ctags" )
967 env.Command( "TAGS", "", findcommand + " |xargs etags" )
968 env.AlwaysBuild( "tags", "TAGS" )
969 if 'NoCache' in dir(env):
970     env.NoCache( "tags", "TAGS" )
971
972 # Another convinience target
973 if env.GetOption( "clean" ):
974     env.Execute( "rm cache/objects -Rf" )
975
976 #
977 # vim: ts=4 sw=4 et
Note: See TracBrowser for help on using the browser.