add liblua wrapper and build-scripts
[ardour.git] / wscript
1 #!/usr/bin/env python
2 from waflib.extras import autowaf as autowaf
3 from waflib import Options
4 import os
5 import re
6 import string
7 import subprocess
8 import sys
9 import platform as PLATFORM
10 from waflib.Tools import winres
11 from waflib.Build import Context
12 from waflib.Build import BuildContext
13
14 class i18n(BuildContext):
15         cmd = 'i18n'
16         fun = 'i18n'
17
18 class i18n_pot(BuildContext):
19         cmd = 'i18n_pot'
20         fun = 'i18n_pot'
21
22 class i18n_po(BuildContext):
23         cmd = 'i18n_po'
24         fun = 'i18n_po'
25
26 class i18n_mo(BuildContext):
27         cmd = 'i18n_mo'
28         fun = 'i18n_mo'
29
30 def is_tracks_build(self, *k, **kw):
31         return self.env['PROGRAM_NAME'] == 'Tracks Live'
32
33 Context.Context.is_tracks_build = is_tracks_build
34
35 compiler_flags_dictionaries= {
36     'gcc' : {
37         # Flags required when building a debug build
38         'debuggable' : [ '-g' ],
39         # Flags required for the linker (if any) when building a debug build
40         'linker-debuggable' : '',
41         # Flags required when building a non-debug optimized build
42         'nondebuggable' : '-DNDEBUG',
43         # Flags required to enable profiling at runtime with optimized builds
44         'profile' : [ '-fno-omit-frame-pointer' ],
45         # Flags required to enable gprofile profiling
46         'gprofile' : '-pg',
47         # Flags required to disable warnings about unused arguments to function calls
48         'silence-unused-arguments' : '',
49         # Flags required to use SSE unit for general math
50         'sse' : '-msse',
51         # Flags required to use SSE unit for floating point math
52         'fpmath-sse' : '-mfpmath=sse',
53         # Flags required to use XMM Intrinsics
54         'xmmintrinsics' : '-DUSE_XMMINTRIN',
55         # Flags to use posix pipes between compiler stages
56         'pipe' : '-pipe',
57         # Flags for maximally optimized build
58         'full-optimization' : [ '-O3', '-fomit-frame-pointer', '-ffast-math', '-fstrength-reduce', ],
59         # Flag to ensure that compiler error output includes column/line numbers
60         'show-column' : '-fshow-column',
61         # Flags required to build for x86 only (OS X feature)
62         'generic-x86' : '',
63         # Flags required to build for PowerPC only (OS X feature)
64         'generic-ppc' : '',
65         # All flags required to get basic warnings to be generated by the compiler
66         'basic-warnings' : [ '-Wall', '-Wpointer-arith', '-Wcast-qual', '-Wcast-align', '-Wno-unused-parameter' ],
67         # Any additional flags for warnings that are specific to C (not C++)
68         'extra-c-warnings' : [ '-Wstrict-prototypes', '-Wmissing-prototypes' ],
69         # Any additional flags for warnings that are specific to C++ (not C)
70         'extra-cxx-warnings' : [ '-Woverloaded-virtual', '-Wno-unused-local-typedefs' ],
71         # Flags used for "strict" compilation, C and C++ (i.e. compiler will warn about language issues)
72         'strict' : ['-Wall', '-Wcast-align', '-Wextra', '-Wwrite-strings', '-Wunsafe-loop-optimizations', '-Wlogical-op' ],
73         # Flags used for "strict" compilation, C only (i.e. compiler will warn about language issues)
74         'c-strict' : ['-std=c99', '-pedantic', '-Wshadow'],
75         # Flags used for "strict" compilation, C++ only (i.e. compiler will warn about language issues)
76         'cxx-strict' : [ '-ansi', '-Wnon-virtual-dtor', '-Woverloaded-virtual', '-fstrict-overflow' ],
77         # Flags required for whatever consider the strictest possible compilation
78         'ultra-strict' : ['-Wredundant-decls', '-Wstrict-prototypes', '-Wmissing-prototypes'],
79         # Flag to turn on C99 compliance by itself
80         'c99': '-std=c99',
81         # Flag to enable AT&T assembler syntax
82         'attasm': '-masm=att',
83         # Flags to make AVX instructions/intrinsics available
84         'avx': '-mavx',
85         # Flags to generate position independent code, when needed to build a shared object
86         'pic': '-fPIC',
87         # Flags required to compile C code with anonymous unions (only part of C11)
88         'c-anonymous-union': '-fms-extensions',
89     },
90     'msvc' : {
91         'debuggable' : ['/DDEBUG', '/Od', '/Zi', '/MDd', '/Gd', '/EHsc'],
92         'linker-debuggable' : ['/DEBUG', '/INCREMENTAL' ],
93         'nondebuggable' : ['/DNDEBUG', '/Ob1', '/MD', '/Gd', '/EHsc'],
94         'profile' : '/Oy-',
95         'sse' : '/arch:SSE',
96         'silence-unused-arguments' : '',
97         'sse' : '',
98         'fpmath-sse' : '',
99         'xmmintrinsics' : '',
100         'pipe' : '',
101         'full-optimization' : '/O2',
102         'no-frame-pointer' : '',
103         'fast-math' : '',
104         'strength-reduce' : '',
105         'show-column' : '',
106         'generic-x86' : '',
107         'generic-ppc' : '',
108         'basic-warnings' : '',
109         'extra-c-warnings' : '',
110         'extra-cxx-warnings' : '',
111         'ultra-strict' : '',
112         'c-strict' : '',
113         'cxx-strict' : '',
114         'strict' : '',
115         'c99': '/TP',
116         'attasm': '',
117         'avx': '',
118         'pic': '',
119         'c-anonymous-union': '',
120     },
121 }
122
123 # Copy, edit and insert variants on gcc dict for gcc-darwin and clang
124
125 gcc_darwin_dict = compiler_flags_dictionaries['gcc'].copy()
126 gcc_darwin_dict['extra-cxx-warnings'] = [ '-Woverloaded-virtual' ]
127 gcc_darwin_dict['cxx-strict'] = [ '-ansi', '-Wnon-virtual-dtor', '-Woverloaded-virtual' ]
128 gcc_darwin_dict['strict'] = ['-Wall', '-Wcast-align', '-Wextra', '-Wwrite-strings' ]
129 gcc_darwin_dict['generic-x86'] = [ '-arch', 'i386' ]
130 gcc_darwin_dict['generic-ppc'] = [ '-arch', 'ppc' ]
131 compiler_flags_dictionaries['gcc-darwin'] = gcc_darwin_dict;
132
133 clang_dict = compiler_flags_dictionaries['gcc'].copy();
134 clang_dict['sse'] = ''
135 clang_dict['fpmath-sse'] = ''
136 clang_dict['xmmintrinsics'] = ''
137 clang_dict['silence-unused-arguments'] = '-Qunused-arguments'
138 clang_dict['extra-cxx-warnings'] = [ '-Woverloaded-virtual', '-Wno-mismatched-tags' ]
139 clang_dict['cxx-strict'] = [ '-ansi', '-Wnon-virtual-dtor', '-Woverloaded-virtual', '-fstrict-overflow' ]
140 clang_dict['strict'] = ['-Wall', '-Wcast-align', '-Wextra', '-Wwrite-strings' ]
141 clang_dict['generic-x86'] = [ '-arch', 'i386' ]
142 compiler_flags_dictionaries['clang'] = clang_dict;
143
144 clang_darwin_dict = compiler_flags_dictionaries['clang'].copy();
145 clang_darwin_dict['cxx-strict'] = [ '-ansi', '-Wnon-virtual-dtor', '-Woverloaded-virtual', ]
146 clang_darwin_dict['full-optimization'] = [ '-O3', '-ffast-math', '-fstrength-reduce' ]
147 compiler_flags_dictionaries['clang-darwin'] = clang_darwin_dict;
148
149 def fetch_git_revision ():
150     cmd = "git describe HEAD | sed 's/^[A-Za-z]*+//'"
151     output = subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0].splitlines()
152     rev = output[0].decode ('utf-8')
153     return rev
154
155 def fetch_tarball_revision ():
156     if not os.path.exists ('libs/ardour/revision.cc'):
157         print ('This tarball was not created correctly - it is missing libs/ardour/revision.cc')
158         sys.exit (1)
159     with open('libs/ardour/revision.cc') as f:
160         content = f.readlines()
161         remove_punctuation_map = dict((ord(char), None) for char in '";')
162         return content[1].decode('utf-8').strip().split(' ')[7].translate (remove_punctuation_map)
163
164 if os.path.isdir (os.path.join(os.getcwd(), '.git')):
165     rev = fetch_git_revision ()
166 else:
167     rev = fetch_tarball_revision ()
168
169 #
170 # rev is now of the form MAJOR.MINOR[-rcX]-rev-commit
171 # or, if right at the same rev as a release, MAJOR.MINOR[-rcX]
172 #
173
174 parts = rev.split ('.', 1)
175 MAJOR = parts[0]
176 other = parts[1].split('-', 1)
177 MINOR = other[0]
178 if len(other) > 1:
179     MICRO = other[1].rsplit('-',1)[0].replace('-','.')
180 else:
181     MICRO = '0'
182
183 V = MAJOR + '.' + MINOR + '.' + MICRO
184 # Ensure that these are not unicode, which
185 # can cause odd problems elsewhere. Note that
186 # in python3, encode and decode do not return
187 # strings, so we have to force the type.
188 VERSION = V.encode ('ascii', 'ignore').decode ("utf-8")
189 PROGRAM_VERSION = MAJOR.encode ('ascii', 'ignore').decode ("utf-8")
190
191 if len (sys.argv) > 1 and sys.argv[1] == 'dist':
192         if not 'APPNAME' in os.environ:
193                 print ("You must define APPNAME in the environment when running ./waf dist")
194                 sys.exit (1)
195         APPNAME = os.environ['APPNAME'];
196
197 # Mandatory variables
198 top = '.'
199 out = 'build'
200
201 children = [
202         # optionally external libraries
203         'libs/qm-dsp',
204         'libs/vamp-plugins',
205         'libs/libltc',
206         'libs/lua',
207         'libs/ptformat',
208         # core ardour libraries
209         'libs/pbd',
210         'libs/midi++2',
211         'libs/evoral',
212         'libs/surfaces',
213         'libs/panners',
214         'libs/backends',
215         'libs/timecode',
216         'libs/ardour',
217         'libs/gtkmm2ext',
218         'libs/audiographer',
219         'libs/canvas',
220         'libs/plugins/reasonablesynth.lv2',
221         'gtk2_ardour',
222         'export',
223         'midi_maps',
224         'mcp',
225         'patchfiles',
226         'headless',
227         'session_utils',
228         # shared helper binaries (plugin-scanner, exec-wrapper)
229         'libs/fst',
230         'libs/vfork',
231         'libs/ardouralsautil',
232         'cfgtool',
233 ]
234
235 i18n_children = [
236         'gtk2_ardour',
237         'libs/ardour',
238         'libs/gtkmm2ext',
239 ]
240
241 # Version stuff
242
243 def fetch_gcc_version (CC):
244     cmd = "%s --version" % CC
245     output = subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0].splitlines()
246     o = output[0].decode('utf-8')
247     version = o.split(' ')[2].split('.')
248     return version
249
250 def create_stored_revision():
251     rev = ""
252     if os.path.exists('.git'):
253         rev = fetch_git_revision();
254         print("Git version: " + rev + "\n")
255     elif os.path.exists('libs/ardour/revision.cc'):
256         print("Using packaged revision")
257         return
258     else:
259         print("Missing libs/ardour/revision.cc.  Blame the packager.")
260         sys.exit(-1)
261
262     try:
263         #
264         # if you change the format of this, be sure to fix fetch_tarball_revision() above
265         # so that  it still works.
266         #
267         text =  '#include "ardour/revision.h"\n'
268         text += 'namespace ARDOUR { const char* revision = \"%s\"; }\n' % rev
269         print('Writing revision info to libs/ardour/revision.cc using ' + rev)
270         o = open('libs/ardour/revision.cc', 'w')
271         o.write(text)
272         o.close()
273     except IOError:
274         print('Could not open libs/ardour/revision.cc for writing\n')
275         sys.exit(-1)
276
277 def set_compiler_flags (conf,opt):
278     #
279     # Compiler flags and other system-dependent stuff
280     #
281     build_host_supports_sse = False
282
283     # Flags necessary for building
284     compiler_flags = []     # generic
285     c_flags = []            # C-specific
286     cxx_flags = []          # C++-specific
287     linker_flags = []
288
289     # Optimization flags (overridable)
290     optimization_flags = []
291
292     # Debugging flags
293     debug_flags = []
294
295     u = PLATFORM.uname ()
296     cpu = u[4]
297     platform = u[0].lower()
298     version = u[2]
299
300     # waf adds -O0 -g itself. thanks waf!
301     is_clang = conf.check_cxx(fragment = '''
302 #ifndef __clang__
303 #error
304 #endif
305 int main() { return 0; }''',
306                          features  = 'cxx',
307                          mandatory = False,
308                          execute   = False,
309                          msg       = 'Checking for clang')
310
311     if is_clang:
312         if platform == 'darwin':
313             compiler_name = 'clang-darwin'
314         else:
315             compiler_name = 'clang'
316     elif conf.env['MSVC_COMPILER']:
317             compiler_name = 'msvc'
318     else:
319         if platform == 'darwin':
320             compiler_name = 'gcc-darwin'
321         else:
322             compiler_name = 'gcc'
323
324     flags_dict = compiler_flags_dictionaries[compiler_name]
325     # Save the compiler flags because we need them at build time
326     # when we need to add compiler specific flags in certain
327     # libraries
328     conf.env['compiler_flags_dict'] = flags_dict;
329
330     autowaf.set_basic_compiler_flags (conf,flags_dict)
331
332     if conf.options.asan:
333         conf.check_cxx(cxxflags=["-fsanitize=address", "-fno-omit-frame-pointer"], linkflags=["-fsanitize=address"])
334         cxx_flags.append('-fsanitize=address')
335         cxx_flags.append('-fno-omit-frame-pointer')
336         linker_flags.append('-fsanitize=address')
337
338     if opt.gprofile:
339         debug_flags = [ flags_dict['gprofile'] ]
340
341     # OSX
342     if platform == 'darwin':
343         if re.search ("^13[.]", version) != None:
344             conf.env['build_host'] = 'mavericks'
345         elif re.search ("^14[.]", version) != None:
346             conf.env['build_host'] = 'yosemite'
347         elif re.search ("^15[.]", version) != None:
348             conf.env['build_host'] = 'el_capitan'
349         else:
350             conf.env['build_host'] = 'irrelevant'
351
352     # Autodetect
353     if opt.dist_target == 'auto':
354         if platform == 'darwin':
355             # The [.] matches to the dot after the major version, "." would match any character
356             if re.search ("^[0-7][.]", version) != None:
357                 conf.env['build_target'] = 'panther'
358             elif re.search ("^8[.]", version) != None:
359                 conf.env['build_target'] = 'tiger'
360             elif re.search ("^9[.]", version) != None:
361                 conf.env['build_target'] = 'leopard'
362             elif re.search ("^10[.]", version) != None:
363                 conf.env['build_target'] = 'snowleopard'
364             elif re.search ("^11[.]", version) != None:
365                 conf.env['build_target'] = 'lion'
366             elif re.search ("^12[.]", version) != None:
367                 conf.env['build_target'] = 'mountainlion'
368             elif re.search ("^13[.]", version) != None:
369                 conf.env['build_target'] = 'mavericks'
370             elif re.search ("^14[.]", version) != None:
371                 conf.env['build_target'] = 'yosemite'
372             else:
373                 conf.env['build_target'] = 'el_capitan'
374         else:
375             match = re.search(
376                     "(?P<cpu>i[0-6]86|x86_64|powerpc|ppc|ppc64|arm|s390x?)",
377                     cpu)
378             if (match):
379                 conf.env['build_target'] = match.group("cpu")
380                 if re.search("i[0-5]86", conf.env['build_target']):
381                     conf.env['build_target'] = "i386"
382             else:
383                 conf.env['build_target'] = 'none'
384     else:
385         conf.env['build_target'] = opt.dist_target
386
387     if conf.env['build_target'] == 'snowleopard':
388         #
389         # stupid OS X 10.6 has a bug in math.h that prevents llrint and friends
390         # from being visible.
391         #
392         compiler_flags.append ('-U__STRICT_ANSI__')
393
394     if opt.use_libcpp:
395        cxx_flags.append('--stdlib=libc++')
396        linker_flags.append('--stdlib=libc++')
397
398     if conf.options.cxx11 or conf.env['build_host'] in [ 'mavericks', 'yosemite', 'el_capitan' ]:
399         conf.check_cxx(cxxflags=["-std=c++11"])
400         cxx_flags.append('-std=c++11')
401         if platform == "darwin":
402             # Mavericks and later changed the syntax to be used when including Carbon headers,
403             # from requiring a full path to requiring just the header name.
404             cxx_flags.append('-DCARBON_FLAT_HEADERS')
405
406             if not opt.use_libcpp:
407                 cxx_flags.append('--stdlib=libstdc++')
408                 linker_flags.append('--stdlib=libstdc++')
409             # Prevents visibility issues in standard headers
410             conf.define("_DARWIN_C_SOURCE", 1)
411         else:
412             cxx_flags.append('-DBOOST_NO_AUTO_PTR')
413
414
415     if (is_clang and platform == "darwin") or conf.env['build_host'] in ['mavericks', 'yosemite', 'el_capitan']:
416         # Silence warnings about the non-existing osx clang compiler flags
417         # -compatibility_version and -current_version.  These are Waf
418         # generated and not needed with clang
419         c_flags.append("-Qunused-arguments")
420         cxx_flags.append("-Qunused-arguments")
421
422     if (re.search ("(i[0-9]86|x86_64|AMD64)", cpu) != None) and conf.env['build_target'] != 'none':
423
424         #
425         # ARCH_X86 means anything in the x86 family from i386 to x86_64
426         # the compile-time presence of the macro _LP64 is used to
427         # distingush 32 and 64 bit assembler
428         #
429
430         compiler_flags.append ("-DARCH_X86")
431
432         if platform == 'linux' :
433
434             #
435             # determine processor flags via /proc/cpuinfo
436             #
437
438             if conf.env['build_target'] != 'i386':
439
440                 flag_line = os.popen ("cat /proc/cpuinfo | grep '^flags'").read()[:-1]
441                 x86_flags = flag_line.split (": ")[1:][0].split ()
442
443                 if "mmx" in x86_flags:
444                     compiler_flags.append ("-mmmx")
445                 if "sse" in x86_flags:
446                     build_host_supports_sse = True
447                 if "3dnow" in x86_flags:
448                     compiler_flags.append ("-m3dnow")
449
450             if cpu == "i586":
451                 compiler_flags.append ("-march=i586")
452             elif cpu == "i686":
453                 compiler_flags.append ("-march=i686")
454
455         if not is_clang and ((conf.env['build_target'] == 'i686') or (conf.env['build_target'] == 'x86_64')) and build_host_supports_sse:
456             compiler_flags.extend ([ flags_dict['sse'], flags_dict['fpmath-sse'], flags_dict['xmmintrinsics'] ])
457
458         if (conf.env['build_target'] == 'mingw'):
459             if (re.search ("(x86_64|AMD64)", cpu) != None):
460                 # on Windows sse is supported by 64 bit platforms only
461                 build_host_supports_sse = True
462
463                 # mingw GCC compiler to uses at&t (Unix specific) assembler dialect by default
464                 # compiler_flags.append (["--mmnemonic=att", "msyntax=att")
465
466                 compiler_flags.extend ([ flags_dict['sse'], flags_dict['fpmath-sse'], flags_dict['xmmintrinsics'], flags_dict['attasm'] ])
467
468     # end of processor-specific section
469
470     # optimization section
471     if conf.env['FPU_OPTIMIZATION']:
472         if sys.platform == 'darwin':
473             compiler_flags.append("-DBUILD_VECLIB_OPTIMIZATIONS");
474             conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'Accelerate'])
475         elif conf.env['build_target'] == 'i686' or conf.env['build_target'] == 'x86_64':
476                 compiler_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
477         elif conf.env['build_target'] == 'mingw':
478                 # usability of the 64 bit windows assembler depends on the compiler target,
479                 # not the build host, which in turn can only be inferred from the name
480                 # of the compiler.
481                 if re.search ('x86_64-w64', str(conf.env['CC'])) != None:
482                         compiler_flags.append ("-DBUILD_SSE_OPTIMIZATIONS")
483         if not build_host_supports_sse:
484             print("\nWarning: you are building Ardour with SSE support even though your system does not support these instructions. (This may not be an error, especially if you are a package maintainer)")
485
486     # end optimization section
487
488     #
489     # no VST on x86_64
490     #
491
492     if conf.env['build_target'] == 'x86_64' and opt.windows_vst:
493         print("\n\n==================================================")
494         print("64bit Windows VST support on 64bit Linux is experimental.")
495         print("(This version of ardour will not load 32bit VSTs)")
496         print("==================================================\n\n")
497
498     if conf.env['LXVST_SUPPORT'] == True:
499         if conf.env['build_target'] == 'x86_64':
500             compiler_flags.append("-DLXVST_64BIT")
501         else:
502             compiler_flags.append("-DLXVST_32BIT")
503
504     #
505     # a single way to test if we're on OS X
506     #
507
508     if conf.env['build_target'] in ['panther', 'tiger', 'leopard' ]:
509         # force tiger or later, to avoid issues on PPC which defaults
510         # back to 10.1 if we don't tell it otherwise.
511
512         compiler_flags.extend(
513                 ("-DMAC_OS_X_VERSION_MIN_REQUIRED=1040",
514                  '-mmacosx-version-min=10.4'))
515
516     elif conf.env['build_target'] in [ 'snowleopard' ]:
517         compiler_flags.extend(
518                 ("-DMAC_OS_X_VERSION_MIN_REQUIRED=1060",
519                  '-mmacosx-version-min=10.6'))
520
521     elif conf.env['build_target'] in [ 'lion', 'mountainlion' ]:
522         compiler_flags.extend(
523                 ("-DMAC_OS_X_VERSION_MIN_REQUIRED=1070",
524                  '-mmacosx-version-min=10.7'))
525
526     elif conf.env['build_target'] in [ 'mavericks', 'yosemite', 'el_capitan' ]:
527         compiler_flags.extend(
528                 ("-DMAC_OS_X_VERSION_MAX_ALLOWED=1090",
529                  "-mmacosx-version-min=10.8"))
530
531     #
532     # save off CPU element in an env
533     #
534     conf.define ('CONFIG_ARCH', cpu)
535
536     #
537     # ARCH="..." overrides all
538     #
539
540     if opt.arch != None:
541         optimization_flags = opt.arch.split()
542
543     #
544     # prepend boiler plate optimization flags that work on all architectures
545     #
546
547     optimization_flags[:0] = [flags_dict['pipe']]
548
549     # don't prepend optimization flags if "-O<something>" is present
550     prepend_opt_flags = True
551     for flag in optimization_flags:
552         if flag.startswith("-O"):
553             prepend_opt_flags = False
554             break
555
556     if prepend_opt_flags:
557         optimization_flags[:0] = flags_dict['full-optimization']
558
559     if opt.debug_symbols:
560         optimization_flags += flags_dict['debuggable']
561
562     if opt.profile:
563         optimization_flags += flags_dict['profile']
564
565     if opt.stl_debug:
566         cxx_flags.append("-D_GLIBCXX_DEBUG")
567
568     if conf.env['DEBUG_RT_ALLOC']:
569         compiler_flags.append('-DDEBUG_RT_ALLOC')
570         linker_flags.append('-ldl')
571
572     if conf.env['DEBUG_DENORMAL_EXCEPTION']:
573         compiler_flags.append('-DDEBUG_DENORMAL_EXCEPTION')
574
575     if opt.generic:
576         compiler_flags.extend(flags_dict['generic-x86'])
577         linker_flags.extend(flags_dict['generic-x86'])
578
579     if opt.ppc:
580         compiler_flags.extend(flags_dict['generic-ppc'])
581         linker_flags.extend(flags_dict['generic-ppc'])
582
583     #
584     # warnings flags
585     #
586
587     compiler_flags.extend(flags_dict['basic-warnings'])
588
589     c_flags.extend(flags_dict['extra-c-warnings'])
590     cxx_flags.extend (flags_dict['extra-cxx-warnings'])
591
592     #
593     # more boilerplate
594     #
595
596     # need ISOC9X for llabs()
597     compiler_flags.extend(
598         ('-DBOOST_SYSTEM_NO_DEPRECATED', '-D_ISOC9X_SOURCE',
599          '-D_LARGEFILE64_SOURCE', '-D_FILE_OFFSET_BITS=64'))
600     cxx_flags.extend(
601         ('-D__STDC_LIMIT_MACROS', '-D__STDC_FORMAT_MACROS',
602          '-DCANVAS_COMPATIBILITY', '-DCANVAS_DEBUG'))
603
604     if opt.nls:
605         compiler_flags.append('-DENABLE_NLS')
606
607     # use sparingly, prefer runtime profile
608     if Options.options.program_name.lower() == "mixbus":
609         compiler_flags.append ('-DMIXBUS')
610
611     compiler_flags.append ('-DPROGRAM_NAME="' + Options.options.program_name + '"')
612     compiler_flags.append ('-DPROGRAM_VERSION="' + PROGRAM_VERSION + '"')
613
614     conf.env['PROGRAM_NAME'] = Options.options.program_name
615
616     if opt.debug:
617         conf.env.append_value('CFLAGS', debug_flags)
618         conf.env.append_value('CXXFLAGS', debug_flags)
619     else:
620         conf.env.append_value('CFLAGS', optimization_flags)
621         conf.env.append_value('CXXFLAGS', optimization_flags)
622
623     if opt.backtrace:
624         if platform != 'darwin' and not is_clang and not Options.options.dist_target == 'mingw':
625             linker_flags += [ '-rdynamic' ]
626
627     conf.env.append_value('CFLAGS', compiler_flags)
628     conf.env.append_value('CFLAGS', c_flags)
629     conf.env.append_value('CXXFLAGS', compiler_flags)
630     conf.env.append_value('CXXFLAGS', cxx_flags)
631     conf.env.append_value('LINKFLAGS', linker_flags)
632
633 def is_tracks_build (conf):
634         return conf.env['PROGRAM_NAME'] == 'Tracks Live'
635
636 #----------------------------------------------------------------
637
638 # Waf stages
639
640 def options(opt):
641     opt.load('compiler_c')
642     opt.load('compiler_cxx')
643     autowaf.set_options(opt, debug_by_default=True)
644     opt.add_option('--program-name', type='string', action='store', default='Ardour', dest='program_name',
645                     help='The user-visible name of the program being built')
646     opt.add_option('--arch', type='string', action='store', dest='arch',
647                     help='Architecture-specific compiler FLAGS')
648     opt.add_option('--with-backends', type='string', action='store', default='jack', dest='with_backends',
649                     help='Specify which backend modules are to be included(jack,alsa,dummy,portaudio,coreaudio)')
650     opt.add_option('--backtrace', action='store_true', default=False, dest='backtrace',
651                     help='Compile with -rdynamic -- allow obtaining backtraces from within Ardour')
652     opt.add_option('--no-carbon', action='store_true', default=False, dest='nocarbon',
653                     help='Compile without support for AU Plugins with only CARBON UI (needed for 64bit)')
654     opt.add_option('--boost-sp-debug', action='store_true', default=False, dest='boost_sp_debug',
655                     help='Compile with Boost shared pointer debugging')
656     opt.add_option('--debug-symbols', action='store_true', default=False, dest='debug_symbols',
657                     help='Add debug-symbols to optimized builds')
658     opt.add_option('--depstack-root', type='string', default='~', dest='depstack_root',
659                     help='Directory/folder where dependency stack trees (gtk, a3) can be found (defaults to ~)')
660     opt.add_option('--dist-target', type='string', default='auto', dest='dist_target',
661                     help='Specify the target for cross-compiling [auto,none,x86,i386,i686,x86_64,tiger,leopard,mingw,msvc]')
662     opt.add_option('--fpu-optimization', action='store_true', default=True, dest='fpu_optimization',
663                     help='Build runtime checked assembler code (default)')
664     opt.add_option('--no-fpu-optimization', action='store_false', dest='fpu_optimization')
665     opt.add_option('--exports-hidden', action='store_true', default=False, dest='exports_hidden')
666     opt.add_option('--freedesktop', action='store_true', default=False, dest='freedesktop',
667                     help='Build MIME type and .desktop files as per freedesktop.org standards (will be placed in build/gtk2_ardour)')
668     opt.add_option('--freebie', action='store_true', default=False, dest='freebie',
669                     help='Build a version suitable for distribution as a zero-cost binary')
670     opt.add_option('--profile', action='store_true', default=False, dest='profile',
671                     help='Compile for use with profiling tools requiring a frame pointer')
672     opt.add_option('--gprofile', action='store_true', default=False, dest='gprofile',
673                     help='Compile for use with gprofile')
674     opt.add_option('--libjack', type='string', default="auto", dest='libjack_link',
675                     help='libjack link mode  [auto|link|weak]')
676     opt.add_option('--internal-shared-libs', action='store_true', default=True, dest='internal_shared_libs',
677                    help='Build internal libs as shared libraries')
678     opt.add_option('--internal-static-libs', action='store_false', dest='internal_shared_libs',
679                    help='Build internal libs as static libraries')
680     opt.add_option('--use-external-libs', action='store_true', default=False, dest='use_external_libs',
681                    help='Use external/system versions of some bundled libraries')
682     opt.add_option('--lv2', action='store_true', default=True, dest='lv2',
683                     help='Compile with support for LV2 (if Lilv+Suil is available)')
684     opt.add_option('--no-lv2', action='store_false', dest='lv2',
685                     help='Do not compile with support for LV2')
686     opt.add_option('--lv2dir', type='string', help="install destination for builtin LV2 bundles [Default: LIBDIR/lv2]")
687     opt.add_option('--lxvst', action='store_true', default=True, dest='lxvst',
688                     help='Compile with support for linuxVST plugins')
689     opt.add_option('--no-lxvst', action='store_false', dest='lxvst',
690                     help='Compile without support for linuxVST plugins')
691     opt.add_option('--no-lrdf', action='store_true', dest='no_lrdf',
692                     help='Compile without support for LRDF LADSPA data even if present')
693     opt.add_option('--nls', action='store_true', default=True, dest='nls',
694                     help='Enable i18n (native language support) (default)')
695     opt.add_option('--no-nls', action='store_false', dest='nls')
696     opt.add_option('--phone-home', action='store_true', default=True, dest='phone_home',
697                    help='Contact ardour.org at startup for new announcements')
698     opt.add_option('--no-phone-home', action='store_false', dest='phone_home',
699                    help='Do not contact ardour.org at startup for new announcements')
700     opt.add_option('--stl-debug', action='store_true', default=False, dest='stl_debug',
701                     help='Build with debugging for the STL')
702     opt.add_option('--rt-alloc-debug', action='store_true', default=False, dest='rt_alloc_debug',
703                     help='Build with debugging for memory allocation in the real-time thread')
704     opt.add_option('--pt-timing', action='store_true', default=False, dest='pt_timing',
705                     help='Build with logging of timing in the process thread(s)')
706     opt.add_option('--denormal-exception', action='store_true', default=False, dest='denormal_exception',
707                     help='Raise a floating point exception if a denormal is detected')
708     opt.add_option('--test', action='store_true', default=False, dest='build_tests',
709                     help="Build unit tests")
710     opt.add_option('--run-tests', action='store_true', default=False, dest='run_tests',
711                     help="Run tests after build")
712     opt.add_option('--single-tests', action='store_true', default=False, dest='single_tests',
713                     help="Build a single executable for each unit test")
714     #opt.add_option('--tranzport', action='store_true', default=False, dest='tranzport',
715     # help='Compile with support for Frontier Designs Tranzport (if libusb is available)')
716     opt.add_option('--generic', action='store_true', default=False, dest='generic',
717                     help='Compile with -arch i386 (OS X ONLY)')
718     opt.add_option('--ppc', action='store_true', default=False, dest='ppc',
719                     help='Compile with -arch ppc (OS X ONLY)')
720     opt.add_option('--versioned', action='store_true', default=False, dest='versioned',
721                     help='Add revision information to executable name inside the build directory')
722     opt.add_option('--windows-vst', action='store_true', default=False, dest='windows_vst',
723                     help='Compile with support for Windows VST')
724     opt.add_option('--windows-key', type='string', action='store', dest='windows_key', default='Mod4><Super',
725                     help='X Modifier(s) (Mod1,Mod2, etc) for the Windows key (X11 builds only). ' +
726                     'Multiple modifiers must be separated by \'><\'')
727     opt.add_option('--boost-include', type='string', action='store', dest='boost_include', default='',
728                     help='directory where Boost header files can be found')
729     opt.add_option('--also-include', type='string', action='store', dest='also_include', default='',
730                     help='additional include directory where header files can be found (split multiples with commas)')
731     opt.add_option('--also-libdir', type='string', action='store', dest='also_libdir', default='',
732                     help='additional include directory where shared libraries can be found (split multiples with commas)')
733     opt.add_option('--wine-include', type='string', action='store', dest='wine_include', default='/usr/include/wine/windows',
734                     help='directory where Wine\'s Windows header files can be found')
735     opt.add_option('--noconfirm', action='store_true', default=False, dest='noconfirm',
736                     help='Do not ask questions that require confirmation during the build')
737     opt.add_option('--cxx11', action='store_true', default=False, dest='cxx11',
738                     help='Turn on c++11 compiler flags (-std=c++11)')
739     opt.add_option('--use-libc++', action='store_true', default=False, dest='use_libcpp',
740                     help='use libc++ instead of default or auto-detected stdlib')
741     opt.add_option('--address-sanitizer', action='store_true', default=False, dest='asan',
742                     help='Turn on AddressSanitizer (requires GCC >= 4.8 or clang >= 3.1)')
743     opt.add_option('--ptformat', action='store_true', default=False, dest='ptformat',
744                     help='Turn on PT session import option')
745     opt.add_option('--no-threaded-waveviews', action='store_true', default=False, dest='no_threaded_waveviews',
746                     help='Disable threaded waveview rendering')
747
748     for i in children:
749         opt.recurse(i)
750
751 def sub_config_and_use(conf, name, has_objects = True):
752     conf.recurse(name)
753     autowaf.set_local_lib(conf, name, has_objects)
754
755 def configure(conf):
756     conf.load('compiler_c')
757     conf.load('compiler_cxx')
758     if Options.options.dist_target == 'mingw':
759         conf.load('winres')
760
761     if Options.options.dist_target == 'msvc':
762         conf.env['MSVC_VERSIONS'] = ['msvc 10.0', 'msvc 9.0', 'msvc 8.0', 'msvc 7.1', 'msvc 7.0', 'msvc 6.0', ]
763         conf.env['MSVC_TARGETS'] = ['x64']
764         conf.load('msvc')
765
766     if Options.options.debug:
767         # Nuke user CFLAGS/CXXFLAGS if debug is set (they likely contain -O3, NDEBUG, etc)
768         conf.env['CFLAGS'] = []
769         conf.env['CXXFLAGS'] = []
770
771     # freedesktop translations needs itstool > 1.0.3 (-j option)
772     if Options.options.freedesktop:
773         output = subprocess.Popen("itstool --version", shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0].splitlines()
774         o = output[0].decode('utf-8')
775         itstool = o.split(' ')[0]
776         version = o.split(' ')[1].split('.')
777         # use  distutils.version.StrictVersion  or something python to check >= 1.0.4
778         # but first make sure that all build-hosts (incl. OSX-10.5/PPC) have that python lib.
779         # lazy approach: just use major version 2.X.X
780         if itstool != "itstool" or version[0] < "2":
781             print("--freedesktop requires itstool > 2.0.0 to translate files.")
782             sys.exit(-1)
783
784     conf.env['VERSION'] = VERSION
785     conf.env['MAJOR'] = MAJOR
786     conf.env['MINOR'] = MINOR
787     conf.env['MICRO'] = MICRO
788     conf.line_just = 52
789     autowaf.set_recursive()
790     autowaf.configure(conf)
791     autowaf.display_header('Ardour Configuration')
792
793     # systems with glibc have libintl builtin. systems without require explicit
794     # linkage against libintl.
795     #
796
797     pkg_config_path = os.getenv('PKG_CONFIG_PATH')
798     user_gtk_root = os.path.expanduser (Options.options.depstack_root + '/gtk/inst')
799
800     if pkg_config_path is not None and pkg_config_path.find (user_gtk_root) >= 0:
801         # told to search user_gtk_root
802         prefinclude = ''.join ([ '-I', user_gtk_root + '/include'])
803         preflib = ''.join ([ '-L', user_gtk_root + '/lib'])
804         conf.env.append_value('CFLAGS', [ prefinclude ])
805         conf.env.append_value('CXXFLAGS',  [prefinclude ])
806         conf.env.append_value('LINKFLAGS', [ preflib ])
807         autowaf.display_msg(conf, 'Will build against private GTK dependency stack in ' + user_gtk_root, 'yes')
808     else:
809         autowaf.display_msg(conf, 'Will build against private GTK dependency stack', 'no')
810
811     if sys.platform == 'darwin':
812         conf.define ('NEED_INTL', 1)
813         autowaf.display_msg(conf, 'Will use explicit linkage against libintl in ' + user_gtk_root, 'yes')
814     else:
815         # libintl is part of the system, so use it
816         autowaf.display_msg(conf, 'Will rely on libintl built into libc', 'yes')
817
818     user_ardour_root = os.path.expanduser (Options.options.depstack_root + '/a3/inst')
819     if pkg_config_path is not None and pkg_config_path.find (user_ardour_root) >= 0:
820         # told to search user_ardour_root
821         prefinclude = ''.join ([ '-I', user_ardour_root + '/include'])
822         preflib = ''.join ([ '-L', user_ardour_root + '/lib'])
823         conf.env.append_value('CFLAGS', [ prefinclude ])
824         conf.env.append_value('CXXFLAGS',  [prefinclude ])
825         conf.env.append_value('LINKFLAGS', [ preflib ])
826         autowaf.display_msg(conf, 'Will build against private Ardour dependency stack in ' + user_ardour_root, 'yes')
827     else:
828         autowaf.display_msg(conf, 'Will build against private Ardour dependency stack', 'no')
829
830     if Options.options.freebie:
831         conf.env.append_value ('CFLAGS', '-DSILENCE_AFTER')
832         conf.env.append_value ('CXXFLAGS', '-DSILENCE_AFTER')
833         conf.define ('FREEBIE', 1)
834
835     if Options.options.lv2dir:
836         conf.env['LV2DIR'] = Options.options.lv2dir
837     else:
838         conf.env['LV2DIR'] = os.path.join(conf.env['LIBDIR'], 'ardour' + str(conf.env['MAJOR']), 'LV2')
839
840     conf.env['LV2DIR'] = os.path.normpath(conf.env['LV2DIR'])
841
842     if sys.platform == 'darwin':
843
844         # this is required, potentially, for anything we link and then relocate into a bundle
845         conf.env.append_value('LINKFLAGS', [ '-Xlinker', '-headerpad_max_install_names' ])
846
847         conf.define ('HAVE_COREAUDIO', 1)
848         conf.define ('AUDIOUNIT_SUPPORT', 1)
849
850         conf.define ('TOP_MENUBAR',1)
851
852         # It would be nice to be able to use this to force back-compatibility with 10.4
853         # but even by the time of 11, the 10.4 SDK is no longer available in any normal
854         # way.
855         #
856         #conf.env.append_value('CXXFLAGS_OSX', "-isysroot /Developer/SDKs/MacOSX10.4u.sdk")
857         #conf.env.append_value('CFLAGS_OSX', "-isysroot /Developer/SDKs/MacOSX10.4u.sdk")
858         #conf.env.append_value('LINKFLAGS_OSX', "-sysroot /Developer/SDKs/MacOSX10.4u.sdk")
859         #conf.env.append_value('LINKFLAGS_OSX', "-sysroot /Developer/SDKs/MacOSX10.4u.sdk")
860
861         conf.env.append_value('CXXFLAGS_OSX', "-msse")
862         conf.env.append_value('CFLAGS_OSX', "-msse")
863         conf.env.append_value('CXXFLAGS_OSX', "-msse2")
864         conf.env.append_value('CFLAGS_OSX', "-msse2")
865         #
866         #       TODO: The previous sse flags NEED to be based
867         #       off processor type.  Need to add in a check
868         #       for that.
869         #
870         conf.env.append_value('CXXFLAGS_OSX', '-F/System/Library/Frameworks')
871         conf.env.append_value('CXXFLAGS_OSX', '-F/Library/Frameworks')
872
873         conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'AppKit'])
874         conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'CoreAudio'])
875         conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'CoreAudioKit'])
876         conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'CoreFoundation'])
877         conf.env.append_value('LINKFLAGS_OSX', ['-framework', 'CoreServices'])
878
879         conf.env.append_value('LINKFLAGS_OSX', ['-undefined', 'dynamic_lookup' ])
880         conf.env.append_value('LINKFLAGS_OSX', ['-flat_namespace'])
881
882         conf.env.append_value('CXXFLAGS_AUDIOUNITS', "-DAUDIOUNIT_SUPPORT")
883         conf.env.append_value('LINKFLAGS_AUDIOUNITS', ['-framework', 'AudioToolbox', '-framework', 'AudioUnit'])
884         conf.env.append_value('LINKFLAGS_AUDIOUNITS', ['-framework', 'Cocoa'])
885
886         if (
887                 # osx up to and including 10.6 (uname 10.X.X)
888                 (re.search ("^[1-9][0-9]\.", os.uname()[2]) == None or not re.search ("^10\.", os.uname()[2]) == None)
889                 and (Options.options.generic or Options.options.ppc)
890                 and not Options.options.nocarbon
891            ):
892             conf.env.append_value('CXXFLAGS_AUDIOUNITS', "-DWITH_CARBON")
893             conf.env.append_value('LINKFLAGS_AUDIOUNITS', ['-framework', 'Carbon'])
894         else:
895             print ('No Carbon support available for this build\n')
896
897
898     if Options.options.internal_shared_libs:
899         conf.define('INTERNAL_SHARED_LIBS', 1)
900
901     if Options.options.use_external_libs:
902         conf.define('USE_EXTERNAL_LIBS', 1)
903
904     if Options.options.boost_include != '':
905         conf.env.append_value('CXXFLAGS', '-I' + Options.options.boost_include)
906
907     if Options.options.also_include != '':
908         conf.env.append_value('CXXFLAGS', '-I' + Options.options.also_include)
909         conf.env.append_value('CFLAGS', '-I' + Options.options.also_include)
910
911     if Options.options.also_libdir != '':
912         conf.env.append_value('LDFLAGS', '-L' + Options.options.also_libdir)
913
914     if Options.options.boost_sp_debug:
915         conf.env.append_value('CXXFLAGS', '-DBOOST_SP_ENABLE_DEBUG_HOOKS')
916
917     # executing a test program is n/a when cross-compiling
918     if Options.options.dist_target != 'mingw':
919         if Options.options.dist_target != 'msvc':
920             conf.check_cc(function_name='dlopen', header_name='dlfcn.h', lib='dl', uselib_store='DL')
921         conf.check_cxx(fragment = "#include <boost/version.hpp>\nint main(void) { return (BOOST_VERSION >= 103900 ? 0 : 1); }\n",
922                   execute = "1",
923                   mandatory = True,
924                   msg = 'Checking for boost library >= 1.39',
925                   okmsg = 'ok',
926                   errmsg = 'too old\nPlease install boost version 1.39 or higher.')
927
928     if re.search ("linux", sys.platform) != None and Options.options.dist_target != 'mingw':
929         autowaf.check_pkg(conf, 'alsa', uselib_store='ALSA')
930
931     autowaf.check_pkg(conf, 'glib-2.0', uselib_store='GLIB', atleast_version='2.28', mandatory=True)
932     autowaf.check_pkg(conf, 'gthread-2.0', uselib_store='GTHREAD', atleast_version='2.2', mandatory=True)
933     autowaf.check_pkg(conf, 'glibmm-2.4', uselib_store='GLIBMM', atleast_version='2.32.0', mandatory=True)
934     autowaf.check_pkg(conf, 'sndfile', uselib_store='SNDFILE', atleast_version='1.0.18', mandatory=True)
935     autowaf.check_pkg(conf, 'giomm-2.4', uselib_store='GIOMM', atleast_version='2.2', mandatory=True)
936     autowaf.check_pkg(conf, 'libcurl', uselib_store='CURL', atleast_version='7.0.0', mandatory=True)
937     autowaf.check_pkg(conf, 'liblo', uselib_store='LO', atleast_version='0.26', mandatory=True)
938     autowaf.check_pkg(conf, 'taglib', uselib_store='TAGLIB', atleast_version='1.6', mandatory=True)
939     autowaf.check_pkg(conf, 'vamp-sdk', uselib_store='VAMPSDK', atleast_version='2.1', mandatory=True)
940     autowaf.check_pkg(conf, 'vamp-hostsdk', uselib_store='VAMPHOSTSDK', atleast_version='2.1', mandatory=True)
941     autowaf.check_pkg(conf, 'rubberband', uselib_store='RUBBERBAND', mandatory=True)
942
943     have_rf64_riff_support = conf.check_cc(fragment = '''
944 #include <sndfile.h>
945 int main () { int x = SFC_RF64_AUTO_DOWNGRADE; return 0; }
946 ''',
947                                            features  = 'c',
948                                            mandatory = False,
949                                            execute   = False,
950                                            use = 'SNDFILE',
951                                            msg       = 'Checking for  sndfile RF64=>RIFF support',
952                                            okmsg = 'Found',
953                                            errmsg = 'Not found, no RF64-to-WAV support')
954
955     if have_rf64_riff_support:
956             conf.env.append_value('CXXFLAGS', "-DHAVE_RF64_RIFF")
957             conf.env.append_value('CFLAGS', "-DHAVE_RF64_RIFF")
958
959     if Options.options.dist_target == 'mingw':
960         Options.options.fpu_optimization = True
961         conf.env.append_value('CFLAGS', '-DPLATFORM_WINDOWS')
962         conf.env.append_value('CFLAGS', '-DCOMPILER_MINGW')
963         conf.env.append_value('CXXFLAGS', '-DPLATFORM_WINDOWS')
964         conf.env.append_value('CXXFLAGS', '-DCOMPILER_MINGW')
965         conf.env.append_value('LIB', 'pthread')
966         # needed for at least libsmf
967         conf.check_cc(function_name='htonl', header_name='winsock2.h', lib='ws2_32')
968         conf.env.append_value('LIB', 'ws2_32')
969         conf.env.append_value('LIB', 'winmm')
970         # needed for mingw64 packages, not harmful on normal mingw build
971         conf.env.append_value('LIB', 'intl')
972         conf.check_cc(function_name='regcomp', header_name='regex.h',
973                       lib='regex', uselib_store="REGEX", define_name='HAVE_REGEX_H')
974         # TODO put this only where it is needed
975         conf.env.append_value('LIB', 'regex')
976         # TODO this should only be necessary for a debug build
977         conf.env.append_value('LIB', 'dbghelp')
978
979         # work around GdkDrawable BitBlt performance issue on windows
980         # see http://gareus.org/wiki/ardour_windows_gdk_and_cairo
981         conf.env.append_value('CFLAGS', '-DUSE_CAIRO_IMAGE_SURFACE')
982         conf.env.append_value('CXXFLAGS', '-DUSE_CAIRO_IMAGE_SURFACE')
983         conf.define ('WINDOWS', 1)
984
985         have_ptw_semaphore = conf.check_cc(fragment = '''
986 #include <pthread.h>
987 #include <semaphore.h>
988 int main () { return 0; }
989 ''',
990                                            features  = 'c',
991                                            mandatory = False,
992                                            execute   = False,
993                                            msg       = 'Checking for pthread posix semaphore',
994                                            okmsg     = 'Found',
995                                            errmsg    = 'Not found, falling back to Windows Semaphore.')
996
997         #if have_ptw_semaphore:
998         #    conf.define('USE_PTW32_SEMAPHORE', 1)
999         #    conf.env.append_value('CFLAGS', '-DUSE_PTW32_SEMAPHORE')
1000         #    conf.env.append_value('CXXFLAGS', '-DUSE_PTW32_SEMAPHORE')
1001
1002     if Options.options.dist_target == 'msvc':
1003         conf.env.append_value('CFLAGS', '-DPLATFORM_WINDOWS')
1004         conf.env.append_value('CFLAGS', '-DCOMPILER_MSVC')
1005         conf.env.append_value('CXXFLAGS', '-DPLATFORM_WINDOWS')
1006         conf.env.append_value('CXXFLAGS', '-DCOMPILER_MSVC')
1007         # work around GdkDrawable BitBlt performance issue on windows
1008         # see http://gareus.org/wiki/ardour_windows_gdk_and_cairo
1009         conf.env.append_value('CFLAGS', '-DUSE_CAIRO_IMAGE_SURFACE')
1010         conf.env.append_value('CXXFLAGS', '-DUSE_CAIRO_IMAGE_SURFACE')
1011         # MORE STUFF PROBABLY NEEDED HERE
1012         conf.define ('WINDOWS', 1)
1013
1014     # Tell everyone that this is a waf build
1015
1016     conf.env.append_value('CFLAGS', '-DWAF_BUILD')
1017     conf.env.append_value('CXXFLAGS', '-DWAF_BUILD')
1018
1019     opts = Options.options
1020
1021     # (optionally) Adopt Microsoft-like convention that makes all non-explicitly exported
1022     # symbols invisible (rather than doing this all over the wscripts in the src tree)
1023     #
1024     # This won't apply to MSVC but that hasn't been added as a target yet
1025     #
1026     # We can't do this till all tests are complete, since some fail if this is et.
1027     if opts.exports_hidden:
1028         conf.define ('EXPORT_VISIBILITY_HIDDEN', True)
1029         if opts.internal_shared_libs:
1030             conf.env.append_value ('CXXFLAGS', '-fvisibility=hidden')
1031             conf.env.append_value ('CFLAGS', '-fvisibility=hidden')
1032     else:
1033         conf.define ('EXPORT_VISIBILITY_HIDDEN', False)
1034
1035     # Set up waf environment and C defines
1036     if opts.phone_home:
1037         conf.define('PHONE_HOME', 1)
1038         conf.env['PHONE_HOME'] = True
1039     if opts.fpu_optimization:
1040         conf.env['FPU_OPTIMIZATION'] = True
1041     if opts.freedesktop:
1042         conf.env['FREEDESKTOP'] = True
1043     if opts.nls:
1044         conf.define('ENABLE_NLS', 1)
1045         conf.env['ENABLE_NLS'] = True
1046     if opts.build_tests:
1047         conf.env['BUILD_TESTS'] = True
1048         conf.env['RUN_TESTS'] = opts.run_tests
1049     if opts.single_tests:
1050         conf.env['SINGLE_TESTS'] = opts.single_tests
1051     #if opts.tranzport:
1052     #    conf.env['TRANZPORT'] = 1
1053     if opts.windows_vst:
1054         conf.define('WINDOWS_VST_SUPPORT', 1)
1055         conf.env['WINDOWS_VST_SUPPORT'] = True
1056         if not Options.options.dist_target == 'mingw':
1057             conf.env.append_value('CFLAGS', '-I' + Options.options.wine_include)
1058             conf.env.append_value('CXXFLAGS', '-I' + Options.options.wine_include)
1059             autowaf.check_header(conf, 'cxx', 'windows.h', mandatory = True)
1060     if opts.lxvst:
1061         if sys.platform == 'darwin':
1062             conf.env['LXVST_SUPPORT'] = False
1063         elif Options.options.dist_target == 'mingw':
1064             conf.env['LXVST_SUPPORT'] = False
1065         else:
1066             conf.define('LXVST_SUPPORT', 1)
1067             conf.env['LXVST_SUPPORT'] = True
1068     conf.env['WINDOWS_KEY'] = opts.windows_key
1069     if opts.rt_alloc_debug:
1070         conf.define('DEBUG_RT_ALLOC', 1)
1071         conf.env['DEBUG_RT_ALLOC'] = True
1072     if opts.pt_timing:
1073         conf.define('PT_TIMING', 1)
1074         conf.env['PT_TIMING'] = True
1075     if opts.denormal_exception:
1076         conf.define('DEBUG_DENORMAL_EXCEPTION', 1)
1077         conf.env['DEBUG_DENORMAL_EXCEPTION'] = True
1078     if opts.build_tests:
1079         autowaf.check_pkg(conf, 'cppunit', uselib_store='CPPUNIT', atleast_version='1.12.0', mandatory=True)
1080     if opts.ptformat:
1081         conf.define('PTFORMAT', 1)
1082         conf.env['PTFORMAT'] = True
1083     if opts.no_threaded_waveviews:
1084         conf.define('NO_THREADED_WAVEVIEWS', 1)
1085         conf.env['NO_THREADED_WAVEVIEWS'] = True
1086         
1087     backends = opts.with_backends.split(',')
1088
1089     if not backends:
1090         print("Must configure and build at least one backend")
1091         sys.exit(1)
1092
1093     conf.env['BACKENDS'] = backends
1094     conf.env['BUILD_JACKBACKEND'] = any('jack' in b for b in backends)
1095     conf.env['BUILD_ALSABACKEND'] = any('alsa' in b for b in backends)
1096     conf.env['BUILD_DUMMYBACKEND'] = any('dummy' in b for b in backends)
1097     conf.env['BUILD_PABACKEND'] = any('portaudio' in b for b in backends)
1098     conf.env['BUILD_CORECRAPPITA'] = any('coreaudio' in b for b in backends)
1099
1100     if re.search ("linux", sys.platform) != None and Options.options.dist_target != 'mingw' and conf.env['BUILD_PABACKEND']:
1101         print("PortAudio Backend is not for Linux")
1102         sys.exit(1)
1103
1104     if sys.platform != 'darwin' and conf.env['BUILD_CORECRAPPITA']:
1105         print("Coreaudio backend is only available for OSX")
1106         sys.exit(1)
1107
1108     if re.search ("linux", sys.platform) == None and conf.env['BUILD_ALSABACKEND']:
1109         print("ALSA Backend is only available on Linux")
1110         sys.exit(1)
1111
1112     set_compiler_flags (conf, Options.options)
1113
1114     if sys.platform == 'darwin':
1115         sub_config_and_use(conf, 'libs/appleutility')
1116     elif Options.options.dist_target != 'mingw':
1117         sub_config_and_use(conf, 'tools/sanity_check')
1118         sub_config_and_use(conf, 'tools/gccabicheck')
1119
1120     sub_config_and_use(conf, 'libs/clearlooks-newer')
1121
1122     for i in children:
1123         sub_config_and_use(conf, i)
1124
1125     # Fix utterly braindead FLAC include path to not smash assert.h
1126     conf.env['INCLUDES_FLAC'] = []
1127
1128     config_text = open('libs/ardour/config_text.cc', "w")
1129     config_text.write('''#include "ardour/ardour.h"
1130 namespace ARDOUR {
1131 const char* const ardour_config_info = "\\n\\
1132 ''')
1133
1134     def write_config_text(title, val):
1135         autowaf.display_msg(conf, title, val)
1136         config_text.write(title + ': ')
1137         config_text.write(str(val).replace ('"', '\\"'))
1138         config_text.write("\\n\\\n")
1139
1140     write_config_text('Build documentation',   conf.env['DOCS'])
1141     write_config_text('Debuggable build',      conf.env['DEBUG'])
1142     write_config_text('Export all symbols (backtrace)', opts.backtrace)
1143     write_config_text('Install prefix',        conf.env['PREFIX'])
1144     write_config_text('Strict compiler flags', conf.env['STRICT'])
1145     write_config_text('Internal Shared Libraries', conf.is_defined('INTERNAL_SHARED_LIBS'))
1146     write_config_text('Use External Libraries', conf.is_defined('USE_EXTERNAL_LIBS'))
1147     write_config_text('Library exports hidden', conf.is_defined('EXPORT_VISIBILITY_HIDDEN'))
1148
1149     write_config_text('ALSA DBus Reservation', conf.is_defined('HAVE_DBUS'))
1150     write_config_text('Architecture flags',    opts.arch)
1151     write_config_text('Aubio',                 conf.is_defined('HAVE_AUBIO'))
1152     write_config_text('AudioUnits',            conf.is_defined('AUDIOUNIT_SUPPORT'))
1153     write_config_text('Free/Demo copy',        conf.is_defined('FREEBIE'))
1154     write_config_text('Build target',          conf.env['build_target'])
1155     write_config_text('CoreAudio',             conf.is_defined('HAVE_COREAUDIO'))
1156     write_config_text('CoreAudio 10.5 compat', conf.is_defined('COREAUDIO105'))
1157     write_config_text('Debug RT allocations',  conf.is_defined('DEBUG_RT_ALLOC'))
1158     write_config_text('Debug Symbols',         conf.is_defined('debug_symbols') or conf.env['DEBUG'])
1159     write_config_text('Process thread timing', conf.is_defined('PT_TIMING'))
1160     write_config_text('Denormal exceptions',   conf.is_defined('DEBUG_DENORMAL_EXCEPTION'))
1161     write_config_text('FLAC',                  conf.is_defined('HAVE_FLAC'))
1162     write_config_text('FPU optimization',      opts.fpu_optimization)
1163     write_config_text('Freedesktop files',     opts.freedesktop)
1164     write_config_text('Libjack linking',       conf.env['libjack_link'])
1165     write_config_text('Libjack metadata',      conf.is_defined ('HAVE_JACK_METADATA'))
1166     write_config_text('LV2 UI embedding',      conf.is_defined('HAVE_SUIL'))
1167     write_config_text('LV2 support',           conf.is_defined('LV2_SUPPORT'))
1168     write_config_text('LXVST support',         conf.is_defined('LXVST_SUPPORT'))
1169     write_config_text('OGG',                   conf.is_defined('HAVE_OGG'))
1170     write_config_text('Phone home',            conf.is_defined('PHONE_HOME'))
1171     write_config_text('Program name',          opts.program_name)
1172     write_config_text('Samplerate',            conf.is_defined('HAVE_SAMPLERATE'))
1173     write_config_text('PT format',             conf.is_defined('PTFORMAT'))
1174     write_config_text('PTW32 Semaphore',       conf.is_defined('USE_PTW32_SEMAPHORE'))
1175 #    write_config_text('Soundtouch',            conf.is_defined('HAVE_SOUNDTOUCH'))
1176     write_config_text('Translation',           opts.nls)
1177 #    write_config_text('Tranzport',             opts.tranzport)
1178     write_config_text('Unit tests',            conf.env['BUILD_TESTS'])
1179     write_config_text('Mac i386 Architecture', opts.generic)
1180     write_config_text('Mac ppc Architecture',  opts.ppc)
1181     write_config_text('Windows VST support',   opts.windows_vst)
1182     write_config_text('Wiimote support',       conf.is_defined('BUILD_WIIMOTE'))
1183     write_config_text('Windows key',           opts.windows_key)
1184
1185     print ('\nBackends:')
1186     
1187     write_config_text('PortAudio Backend',     conf.env['BUILD_PABACKEND'])
1188     write_config_text('CoreAudio/Midi Backend',conf.env['BUILD_CORECRAPPITA'])
1189     write_config_text('ALSA Backend',          conf.env['BUILD_ALSABACKEND'])
1190     write_config_text('Dummy backend',         conf.env['BUILD_DUMMYBACKEND'])
1191     write_config_text('JACK Backend',          conf.env['BUILD_JACKBACKEND'])
1192
1193     print ('\n')
1194     
1195     write_config_text('C compiler flags',      conf.env['CFLAGS'])
1196     write_config_text('C++ compiler flags',    conf.env['CXXFLAGS'])
1197     write_config_text('Linker flags',          conf.env['LINKFLAGS'])
1198
1199     config_text.write ('";\n}\n')
1200     config_text.close ()
1201     print('')
1202
1203 def build(bld):
1204     create_stored_revision()
1205
1206     # add directories that contain only headers, to workaround an issue with waf
1207
1208     if not bld.is_defined('USE_EXTERNAL_LIBS'):
1209         bld.path.find_dir ('libs/libltc/ltc')
1210     bld.path.find_dir ('libs/evoral/evoral')
1211     bld.path.find_dir ('libs/surfaces/control_protocol/control_protocol')
1212     bld.path.find_dir ('libs/timecode/timecode')
1213     bld.path.find_dir ('libs/gtkmm2ext/gtkmm2ext')
1214     bld.path.find_dir ('libs/ardour/ardour')
1215     bld.path.find_dir ('libs/pbd/pbd')
1216
1217     # set up target directories
1218     lwrcase_dirname = 'ardour' + bld.env['MAJOR']
1219
1220     if bld.is_tracks_build():
1221         bld.env.append_value ('CXXFLAGS', '-DUSE_TRACKS_CODE_FEATURES')
1222         bld.env.append_value ('CFLAGS', '-DUSE_TRACKS_CODE_FEATURES')
1223         lwrcase_dirname = 'trx'
1224
1225     # configuration files go here
1226     bld.env['CONFDIR'] = os.path.join(bld.env['SYSCONFDIR'], lwrcase_dirname)
1227     # data files loaded at run time go here
1228     bld.env['DATADIR'] = os.path.join(bld.env['DATADIR'], lwrcase_dirname)
1229     # shared objects loaded at runtime go here (two aliases)
1230     bld.env['DLLDIR'] = os.path.join(bld.env['LIBDIR'], lwrcase_dirname)
1231     bld.env['LIBDIR'] = bld.env['DLLDIR']
1232     bld.env['LOCALEDIR'] = os.path.join(bld.env['DATADIR'], 'locale')
1233     bld.env['lwrcase_dirname'] = lwrcase_dirname;
1234
1235     autowaf.set_recursive()
1236
1237     if sys.platform == 'darwin':
1238         bld.recurse('libs/appleutility')
1239     elif bld.env['build_target'] != 'mingw':
1240         bld.recurse('tools/sanity_check')
1241         bld.recurse('tools/gccabicheck')
1242
1243     bld.recurse('libs/clearlooks-newer')
1244
1245     for i in children:
1246         bld.recurse(i)
1247
1248     bld.install_files (bld.env['CONFDIR'], 'system_config')
1249
1250     if bld.env['RUN_TESTS']:
1251         bld.add_post_fun(test)
1252
1253 def i18n(bld):
1254     print(bld.env)
1255     bld.recurse (i18n_children)
1256
1257 def i18n_pot(bld):
1258     bld.recurse (i18n_children)
1259
1260 def i18n_po(bld):
1261     bld.recurse (i18n_children)
1262
1263 def i18n_mo(bld):
1264     bld.recurse (i18n_children)
1265
1266 def tarball(bld):
1267     create_stored_revision()
1268
1269 def test(bld):
1270     subprocess.call("gtk2_ardour/artest")