python/lib/moresetuptools.py: add get_aubio_version and get_aubio_pyversion
[aubio.git] / python / lib / moresetuptools.py
1 """ A collection of function used from setup.py distutils script """
2 #
3 import sys, os, glob, subprocess
4 import distutils, distutils.command.clean, distutils.dir_util
5 from .gen_external import generate_external, header, output_path
6
7 def get_aubio_version():
8     # read from VERSION
9     this_file_dir = os.path.dirname(os.path.abspath(__file__))
10     version_file = os.path.join(this_file_dir, '..', '..', 'VERSION')
11
12     if not os.path.isfile(version_file):
13         raise SystemError("VERSION file not found.")
14
15     for l in open(version_file).readlines():
16         #exec (l.strip())
17         if l.startswith('AUBIO_MAJOR_VERSION'):
18             AUBIO_MAJOR_VERSION = int(l.split('=')[1])
19         if l.startswith('AUBIO_MINOR_VERSION'):
20             AUBIO_MINOR_VERSION = int(l.split('=')[1])
21         if l.startswith('AUBIO_PATCH_VERSION'):
22             AUBIO_PATCH_VERSION = int(l.split('=')[1])
23         if l.startswith('AUBIO_VERSION_STATUS'):
24             AUBIO_VERSION_STATUS = l.split('=')[1].strip()[1:-1]
25
26     if AUBIO_MAJOR_VERSION is None or AUBIO_MINOR_VERSION is None \
27             or AUBIO_PATCH_VERSION is None:
28         raise SystemError("Failed parsing VERSION file.")
29
30     verstr = '.'.join(map(str, [AUBIO_MAJOR_VERSION,
31                                      AUBIO_MINOR_VERSION,
32                                      AUBIO_PATCH_VERSION]))
33
34     if AUBIO_VERSION_STATUS is not None:
35         verstr += AUBIO_VERSION_STATUS
36     return verstr
37
38 def get_aubio_pyversion():
39     verstr = get_aubio_version()
40     if '~alpha' in verstr:
41         verstr = verstr.split('~')[0] + 'a1'
42     return verstr
43
44 # inspired from https://gist.github.com/abergmeier/9488990
45 def add_packages(packages, ext=None, **kw):
46     """ use pkg-config to search which of 'packages' are installed """
47     flag_map = {
48         '-I': 'include_dirs',
49         '-L': 'library_dirs',
50         '-l': 'libraries'}
51
52     # if a setuptools extension is passed, fill it with pkg-config results
53     if ext:
54         kw = {'include_dirs': ext.include_dirs,
55               'extra_link_args': ext.extra_link_args,
56               'library_dirs': ext.library_dirs,
57               'libraries': ext.libraries,
58              }
59
60     for package in packages:
61         print("checking for {:s}".format(package))
62         cmd = ['pkg-config', '--libs', '--cflags', package]
63         try:
64             tokens = subprocess.check_output(cmd)
65         except Exception as e:
66             print("Running \"{:s}\" failed: {:s}".format(' '.join(cmd), repr(e)))
67             continue
68         tokens = tokens.decode('utf8').split()
69         for token in tokens:
70             key = token[:2]
71             try:
72                 arg = flag_map[key]
73                 value = token[2:]
74             except KeyError:
75                 arg = 'extra_link_args'
76                 value = token
77             kw.setdefault(arg, []).append(value)
78     for key, value in iter(kw.items()): # remove duplicated
79         kw[key] = list(set(value))
80     return kw
81
82 def add_local_aubio_header(ext):
83     """ use local "src/aubio.h", not <aubio/aubio.h>"""
84     ext.define_macros += [('USE_LOCAL_AUBIO', 1)]
85     ext.include_dirs += ['src'] # aubio.h
86
87 def add_local_aubio_lib(ext):
88     """ add locally built libaubio from build/src """
89     print("Info: using locally built libaubio")
90     ext.library_dirs += [os.path.join('build', 'src')]
91     ext.libraries += ['aubio']
92
93 def add_local_aubio_sources(ext, usedouble = False):
94     """ build aubio inside python module instead of linking against libaubio """
95     print("Info: libaubio was not installed or built locally with waf, adding src/")
96     aubio_sources = sorted(glob.glob(os.path.join('src', '**.c')))
97     aubio_sources += sorted(glob.glob(os.path.join('src', '*', '**.c')))
98     ext.sources += aubio_sources
99
100 def add_local_macros(ext, usedouble = False):
101     # define macros (waf puts them in build/src/config.h)
102     for define_macro in ['HAVE_STDLIB_H', 'HAVE_STDIO_H',
103                          'HAVE_MATH_H', 'HAVE_STRING_H',
104                          'HAVE_C99_VARARGS_MACROS',
105                          'HAVE_LIMITS_H', 'HAVE_STDARG_H',
106                          'HAVE_MEMCPY_HACKS']:
107         ext.define_macros += [(define_macro, 1)]
108
109 def add_external_deps(ext, usedouble = False):
110     # loof for additional packages
111     print("Info: looking for *optional* additional packages")
112     packages = ['libavcodec', 'libavformat', 'libavutil', 'libavresample',
113                 'jack',
114                 'jack',
115                 'sndfile',
116                 #'fftw3f',
117                ]
118     # samplerate only works with float
119     if usedouble == False:
120         packages += ['samplerate']
121     else:
122         print("Info: not adding libsamplerate in double precision mode")
123     add_packages(packages, ext=ext)
124     if 'avcodec' in ext.libraries \
125             and 'avformat' in ext.libraries \
126             and 'avutil' in ext.libraries \
127             and 'avresample' in ext.libraries:
128         ext.define_macros += [('HAVE_LIBAV', 1)]
129     if 'jack' in ext.libraries:
130         ext.define_macros += [('HAVE_JACK', 1)]
131     if 'sndfile' in ext.libraries:
132         ext.define_macros += [('HAVE_SNDFILE', 1)]
133     if 'samplerate' in ext.libraries:
134         ext.define_macros += [('HAVE_SAMPLERATE', 1)]
135     if 'fftw3f' in ext.libraries:
136         ext.define_macros += [('HAVE_FFTW3F', 1)]
137         ext.define_macros += [('HAVE_FFTW3', 1)]
138
139     # add accelerate on darwin
140     if sys.platform.startswith('darwin'):
141         ext.extra_link_args += ['-framework', 'Accelerate']
142         ext.define_macros += [('HAVE_ACCELERATE', 1)]
143         ext.define_macros += [('HAVE_SOURCE_APPLE_AUDIO', 1)]
144         ext.define_macros += [('HAVE_SINK_APPLE_AUDIO', 1)]
145
146     if sys.platform.startswith('win'):
147         ext.define_macros += [('HAVE_WIN_HACKS', 1)]
148
149     ext.define_macros += [('HAVE_WAVWRITE', 1)]
150     ext.define_macros += [('HAVE_WAVREAD', 1)]
151     # TODO:
152     # add cblas
153     if 0:
154         ext.libraries += ['cblas']
155         ext.define_macros += [('HAVE_ATLAS_CBLAS_H', 1)]
156
157 def add_system_aubio(ext):
158     # use pkg-config to find aubio's location
159     add_packages(['aubio'], ext)
160     if 'aubio' not in ext.libraries:
161         print("Error: libaubio not found")
162
163 class CleanGenerated(distutils.command.clean.clean):
164     def run(self):
165         if os.path.isdir(output_path):
166             distutils.dir_util.remove_tree(output_path)
167
168 from distutils.command.build_ext import build_ext as _build_ext
169 class build_ext(_build_ext):
170
171     user_options = _build_ext.user_options + [
172             # The format is (long option, short option, description).
173             ('enable-double', None, 'use HAVE_AUBIO_DOUBLE=1 (default: 0)'),
174             ]
175
176     def initialize_options(self):
177         _build_ext.initialize_options(self)
178         self.enable_double = False
179
180     def finalize_options(self):
181         _build_ext.finalize_options(self)
182         if self.enable_double:
183             self.announce(
184                     'will generate code for aubio compiled with HAVE_AUBIO_DOUBLE=1',
185                     level=distutils.log.INFO)
186
187     def build_extension(self, extension):
188         if self.enable_double or 'HAVE_AUBIO_DOUBLE' in os.environ:
189             extension.define_macros += [('HAVE_AUBIO_DOUBLE', 1)]
190             enable_double = True
191         else:
192             enable_double = False
193         # seack for aubio headers and lib in PKG_CONFIG_PATH
194         add_system_aubio(extension)
195         # the lib was not installed on this system
196         if 'aubio' not in extension.libraries:
197             # use local src/aubio.h
198             if os.path.isfile(os.path.join('src', 'aubio.h')):
199                 add_local_aubio_header(extension)
200             add_local_macros(extension)
201             # look for a local waf build
202             if os.path.isfile(os.path.join('build','src', 'fvec.c.1.o')):
203                 add_local_aubio_lib(extension)
204             else:
205                 # check for external dependencies
206                 add_external_deps(extension, usedouble=enable_double)
207                 # add libaubio sources and look for optional deps with pkg-config
208                 add_local_aubio_sources(extension, usedouble=enable_double)
209         # generate files python/gen/*.c, python/gen/aubio-generated.h
210         extension.sources += generate_external(header, output_path, overwrite = False,
211                 usedouble=enable_double)
212         return _build_ext.build_extension(self, extension)