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