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