source: python/lib/moresetuptools.py @ 227aa1c

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5sampleryinfft+
Last change on this file since 227aa1c was 227aa1c, checked in by Paul Brossier <piem@piem.org>, 7 years ago

python/lib/moresetuptools.py: use system aubio only when version matches exactly (closes: #84)

  • Property mode set to 100644
File size: 8.4 KB
Line 
1""" A collection of function used from setup.py distutils script """
2#
3import sys, os, glob, subprocess
4import distutils, distutils.command.clean, distutils.dir_util
5from .gen_external import generate_external, header, output_path
6
7def 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
38def 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
45def 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
82def 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
87def 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
93def 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
100def 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
109def 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
157def add_system_aubio(ext):
158    # use pkg-config to find aubio's location
159    aubio_version = get_aubio_version()
160    add_packages(['aubio = ' + aubio_version], ext)
161    if 'aubio' not in ext.libraries:
162        print("Info: aubio " + aubio_version + " was not found by pkg-config")
163    else:
164        print("Info: using system aubio " + aubio_version + " found in " + ' '.join(ext.library_dirs))
165
166class CleanGenerated(distutils.command.clean.clean):
167    def run(self):
168        if os.path.isdir(output_path):
169            distutils.dir_util.remove_tree(output_path)
170
171from distutils.command.build_ext import build_ext as _build_ext
172class build_ext(_build_ext):
173
174    user_options = _build_ext.user_options + [
175            # The format is (long option, short option, description).
176            ('enable-double', None, 'use HAVE_AUBIO_DOUBLE=1 (default: 0)'),
177            ]
178
179    def initialize_options(self):
180        _build_ext.initialize_options(self)
181        self.enable_double = False
182
183    def finalize_options(self):
184        _build_ext.finalize_options(self)
185        if self.enable_double:
186            self.announce(
187                    'will generate code for aubio compiled with HAVE_AUBIO_DOUBLE=1',
188                    level=distutils.log.INFO)
189
190    def build_extension(self, extension):
191        if self.enable_double or 'HAVE_AUBIO_DOUBLE' in os.environ:
192            extension.define_macros += [('HAVE_AUBIO_DOUBLE', 1)]
193            enable_double = True
194        else:
195            enable_double = False
196        # seack for aubio headers and lib in PKG_CONFIG_PATH
197        add_system_aubio(extension)
198        # the lib was not installed on this system
199        if 'aubio' not in extension.libraries:
200            # use local src/aubio.h
201            if os.path.isfile(os.path.join('src', 'aubio.h')):
202                add_local_aubio_header(extension)
203            add_local_macros(extension)
204            # look for a local waf build
205            if os.path.isfile(os.path.join('build','src', 'fvec.c.1.o')):
206                add_local_aubio_lib(extension)
207            else:
208                # check for external dependencies
209                add_external_deps(extension, usedouble=enable_double)
210                # add libaubio sources and look for optional deps with pkg-config
211                add_local_aubio_sources(extension, usedouble=enable_double)
212        # generate files python/gen/*.c, python/gen/aubio-generated.h
213        extension.sources += generate_external(header, output_path, overwrite = False,
214                usedouble=enable_double)
215        return _build_ext.build_extension(self, extension)
Note: See TracBrowser for help on using the repository browser.