source: python/lib/moresetuptools.py @ cf19b8a

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

python/lib/moresetuptools.py: cleaner clean

  • Property mode set to 100644
File size: 6.7 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
7# inspired from https://gist.github.com/abergmeier/9488990
8def add_packages(packages, ext=None, **kw):
9    """ use pkg-config to search which of 'packages' are installed """
10    flag_map = {
11        '-I': 'include_dirs',
12        '-L': 'library_dirs',
13        '-l': 'libraries'}
14
15    # if a setuptools extension is passed, fill it with pkg-config results
16    if ext:
17        kw = {'include_dirs': ext.include_dirs,
18              'extra_link_args': ext.extra_link_args,
19              'library_dirs': ext.library_dirs,
20              'libraries': ext.libraries,
21             }
22
23    for package in packages:
24        cmd = ['pkg-config', '--libs', '--cflags', package]
25        try:
26            tokens = subprocess.check_output(cmd)
27        except Exception as e:
28            print("Running \"{:s}\" failed: {:s}".format(' '.join(cmd), repr(e)))
29            continue
30        tokens = tokens.decode('utf8').split()
31        for token in tokens:
32            key = token[:2]
33            try:
34                arg = flag_map[key]
35                value = token[2:]
36            except KeyError:
37                arg = 'extra_link_args'
38                value = token
39            kw.setdefault(arg, []).append(value)
40    for key, value in iter(kw.items()): # remove duplicated
41        kw[key] = list(set(value))
42    return kw
43
44def add_local_aubio_header(ext):
45    """ use local "src/aubio.h", not <aubio/aubio.h>"""
46    ext.define_macros += [('USE_LOCAL_AUBIO', 1)]
47    ext.include_dirs += ['src'] # aubio.h
48
49def add_local_aubio_lib(ext):
50    """ add locally built libaubio from build/src """
51    print("Info: using locally built libaubio")
52    ext.library_dirs += [os.path.join('build', 'src')]
53    ext.libraries += ['aubio']
54
55def add_local_aubio_sources(ext, usedouble = False):
56    """ build aubio inside python module instead of linking against libaubio """
57    print("Warning: libaubio was not built with waf, adding src/")
58    # create an empty header, macros will be passed on the command line
59    fake_config_header = os.path.join('python', 'ext', 'config.h')
60    distutils.file_util.write_file(fake_config_header, "")
61    aubio_sources = sorted(glob.glob(os.path.join('src', '**.c')))
62    aubio_sources += sorted(glob.glob(os.path.join('src', '*', '**.c')))
63    ext.sources += aubio_sources
64    # define macros (waf puts them in build/src/config.h)
65    for define_macro in ['HAVE_STDLIB_H', 'HAVE_STDIO_H',
66                         'HAVE_MATH_H', 'HAVE_STRING_H',
67                         'HAVE_C99_VARARGS_MACROS',
68                         'HAVE_LIMITS_H', 'HAVE_STDARG_H',
69                         'HAVE_MEMCPY_HACKS']:
70        ext.define_macros += [(define_macro, 1)]
71
72    # loof for additional packages
73    print("Info: looking for *optional* additional packages")
74    packages = ['libavcodec', 'libavformat', 'libavutil', 'libavresample',
75                'jack',
76                'jack',
77                'sndfile',
78                #'fftw3f',
79               ]
80    # samplerate only works with float
81    if usedouble == False:
82        packages += ['samplerate']
83    else:
84        print("Info: not adding libsamplerate in double precision mode")
85    add_packages(packages, ext=ext)
86    if 'avcodec' in ext.libraries \
87            and 'avformat' in ext.libraries \
88            and 'avutil' in ext.libraries \
89            and 'avresample' in ext.libraries:
90        ext.define_macros += [('HAVE_LIBAV', 1)]
91    if 'jack' in ext.libraries:
92        ext.define_macros += [('HAVE_JACK', 1)]
93    if 'sndfile' in ext.libraries:
94        ext.define_macros += [('HAVE_SNDFILE', 1)]
95    if 'samplerate' in ext.libraries:
96        ext.define_macros += [('HAVE_SAMPLERATE', 1)]
97    if 'fftw3f' in ext.libraries:
98        ext.define_macros += [('HAVE_FFTW3F', 1)]
99        ext.define_macros += [('HAVE_FFTW3', 1)]
100
101    # add accelerate on darwin
102    if sys.platform.startswith('darwin'):
103        ext.extra_link_args += ['-framework', 'Accelerate']
104        ext.define_macros += [('HAVE_ACCELERATE', 1)]
105        ext.define_macros += [('HAVE_SOURCE_APPLE_AUDIO', 1)]
106        ext.define_macros += [('HAVE_SINK_APPLE_AUDIO', 1)]
107
108    if sys.platform.startswith('win'):
109        ext.define_macros += [('HAVE_WIN_HACKS', 1)]
110
111    ext.define_macros += [('HAVE_WAVWRITE', 1)]
112    ext.define_macros += [('HAVE_WAVREAD', 1)]
113    # TODO:
114    # add cblas
115    if 0:
116        ext.libraries += ['cblas']
117        ext.define_macros += [('HAVE_ATLAS_CBLAS_H', 1)]
118
119def add_system_aubio(ext):
120    # use pkg-config to find aubio's location
121    add_packages(['aubio'], ext)
122    if 'aubio' not in ext.libraries:
123        print("Error: libaubio not found")
124
125class CleanGenerated(distutils.command.clean.clean):
126    def run(self):
127        if os.path.isdir(output_path):
128            distutils.dir_util.remove_tree(output_path)
129        config = os.path.join('python', 'ext', 'config.h')
130        distutils.command.clean.clean.run(self)
131
132from distutils.command.build_ext import build_ext as _build_ext
133class build_ext(_build_ext):
134
135    user_options = _build_ext.user_options + [
136            # The format is (long option, short option, description).
137            ('enable-double', None, 'use HAVE_AUBIO_DOUBLE=1 (default: 0)'),
138            ]
139
140    def initialize_options(self):
141        _build_ext.initialize_options(self)
142        self.enable_double = False
143
144    def finalize_options(self):
145        _build_ext.finalize_options(self)
146        if self.enable_double:
147            self.announce(
148                    'will generate code for aubio compiled with HAVE_AUBIO_DOUBLE=1',
149                    level=distutils.log.INFO)
150
151    def build_extension(self, extension):
152        if self.enable_double:
153            extension.define_macros += [('HAVE_AUBIO_DOUBLE', 1)]
154        if os.path.isfile('src/aubio.h'):
155            # if aubio headers are found in this directory
156            add_local_aubio_header(extension)
157            # was waf used to build the shared lib?
158            if os.path.isdir(os.path.join('build','src')):
159                # link against build/src/libaubio, built with waf
160                add_local_aubio_lib(extension)
161            else:
162                # add libaubio sources and look for optional deps with pkg-config
163                add_local_aubio_sources(extension, usedouble=self.enable_double)
164        else:
165            # look for aubio headers and lib using pkg-config
166            add_system_aubio(extension)
167        # generate files python/gen/*.c, python/gen/aubio-generated.h
168        extension.sources += generate_external(header, output_path, overwrite = False,
169                usedouble=self.enable_double)
170        return _build_ext.build_extension(self, extension)
Note: See TracBrowser for help on using the repository browser.