Tweak how lzma is linked.
[dcpomatic.git] / wscript
1 #
2 #    Copyright (C) 2012-2021 Carl Hetherington <cth@carlh.net>
3 #
4 #    This file is part of DCP-o-matic.
5 #
6 #    DCP-o-matic is free software; you can redistribute it and/or modify
7 #    it under the terms of the GNU General Public License as published by
8 #    the Free Software Foundation; either version 2 of the License, or
9 #    (at your option) any later version.
10 #
11 #    DCP-o-matic is distributed in the hope that it will be useful,
12 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
13 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 #    GNU General Public License for more details.
15 #
16 #    You should have received a copy of the GNU General Public License
17 #    along with DCP-o-matic.  If not, see <http://www.gnu.org/licenses/>.
18 #
19
20 from __future__ import print_function
21
22 import subprocess
23 import os
24 import shlex
25 import sys
26 import glob
27 import distutils
28 import distutils.spawn
29 try:
30     # python 2
31     from urllib import urlencode
32 except ImportError:
33     # python 3
34     from urllib.parse import urlencode
35 from waflib import Logs, Context
36
37 APPNAME = 'dcpomatic'
38 libdcp_version = '1.8.73'
39 libsub_version = '1.6.42'
40
41 this_version = subprocess.Popen(shlex.split('git tag -l --points-at HEAD'), stdout=subprocess.PIPE).communicate()[0]
42 last_version = subprocess.Popen(shlex.split('git describe --tags --match v* --abbrev=0'), stdout=subprocess.PIPE).communicate()[0]
43
44 # Python 2/3 compatibility; I don't really understand what's going on here
45 if not isinstance(this_version, str):
46     this_version = this_version.decode('utf-8')
47 if not isinstance(last_version, str):
48     last_version = last_version.decode('utf-8')
49
50 if this_version == '' or this_version == 'merged-to-main':
51     VERSION = '%sdevel' % last_version[1:].strip()
52 else:
53     VERSION = this_version[1:].strip()
54
55 def options(opt):
56     opt.load('compiler_cxx')
57     opt.load('winres')
58
59     opt.add_option('--enable-debug',      action='store_true', default=False, help='build with debugging information and without optimisation')
60     opt.add_option('--disable-gui',       action='store_true', default=False, help='disable building of GUI tools')
61     opt.add_option('--disable-tests',     action='store_true', default=False, help='disable building of tests')
62     opt.add_option('--target-windows-64', action='store_true', default=False, help='set up to do a cross-compile for Windows 64-bit')
63     opt.add_option('--target-windows-32', action='store_true', default=False, help='set up to do a cross-compile for Windows 32-bit')
64     opt.add_option('--target-macos-arm64', action='store_true', default=False, help='set up to do a cross-compile for macOS arm64')
65     opt.add_option('--static-dcpomatic',  action='store_true', default=False, help='link to components of DCP-o-matic statically')
66     opt.add_option('--static-boost',      action='store_true', default=False, help='link statically to Boost')
67     opt.add_option('--static-wxwidgets',  action='store_true', default=False, help='link statically to wxWidgets')
68     opt.add_option('--static-ffmpeg',     action='store_true', default=False, help='link statically to FFmpeg')
69     opt.add_option('--static-xmlpp',      action='store_true', default=False, help='link statically to libxml++')
70     opt.add_option('--static-xmlsec',     action='store_true', default=False, help='link statically to xmlsec')
71     opt.add_option('--static-ssh',        action='store_true', default=False, help='link statically to libssh')
72     opt.add_option('--static-cxml',       action='store_true', default=False, help='link statically to libcxml')
73     opt.add_option('--static-dcp',        action='store_true', default=False, help='link statically to libdcp')
74     opt.add_option('--static-sub',        action='store_true', default=False, help='link statically to libsub')
75     opt.add_option('--static-curl',       action='store_true', default=False, help='link statically to libcurl')
76     opt.add_option('--workaround-gssapi', action='store_true', default=False, help='link to gssapi_krb5')
77     opt.add_option('--use-lld',           action='store_true', default=False, help='use lld linker')
78     opt.add_option('--enable-disk',       action='store_true', default=False, help='build dcpomatic2_disk tool; requires Boost process, lwext4 and nanomsg libraries')
79     opt.add_option('--warnings-are-errors', action='store_true', default=False, help='build with -Werror')
80     opt.add_option('--wx-config',         help='path to wx-config')
81     opt.add_option('--enable-asan',       action='store_true', help='build with asan')
82
83 def configure(conf):
84     conf.load('compiler_cxx')
85     conf.load('clang_compilation_database', tooldir=['waf-tools'])
86     if conf.options.target_windows_64 or conf.options.target_windows_32:
87         conf.load('winres')
88
89     # Save conf.options that we need elsewhere in conf.env
90     conf.env.DISABLE_GUI = conf.options.disable_gui
91     conf.env.DISABLE_TESTS = conf.options.disable_tests
92     conf.env.TARGET_WINDOWS_64 = conf.options.target_windows_64
93     conf.env.TARGET_WINDOWS_32 = conf.options.target_windows_32
94     conf.env.TARGET_OSX = sys.platform == 'darwin'
95     conf.env.TARGET_LINUX = not conf.env.TARGET_WINDOWS_64 and not conf.env.TARGET_WINDOWS_32 and not conf.env.TARGET_OSX
96     conf.env.VERSION = VERSION
97     conf.env.DEBUG = conf.options.enable_debug
98     conf.env.STATIC_DCPOMATIC = conf.options.static_dcpomatic
99     conf.env.ENABLE_DISK = conf.options.enable_disk
100     if conf.options.destdir == '':
101         conf.env.INSTALL_PREFIX = conf.options.prefix
102     else:
103         conf.env.INSTALL_PREFIX = conf.options.destdir
104
105     # Common CXXFLAGS
106     conf.env.append_value('CXXFLAGS', ['-D__STDC_CONSTANT_MACROS',
107                                        '-D__STDC_LIMIT_MACROS',
108                                        '-D__STDC_FORMAT_MACROS',
109                                        '-fno-strict-aliasing',
110                                        '-Wall',
111                                        '-Wextra',
112                                        '-Wwrite-strings',
113                                        '-Wno-error=deprecated',
114                                        # I tried and failed to ignore these with _Pragma
115                                        '-Wno-ignored-qualifiers',
116                                        '-D_FILE_OFFSET_BITS=64',
117                                        '-std=c++11'])
118
119     if conf.options.warnings_are_errors:
120         conf.env.append_value('CXXFLAGS', '-Werror')
121
122     if not conf.options.target_macos_arm64:
123         conf.env.append_value('CXXFLAGS', '-msse')
124
125     if conf.options.enable_asan:
126         conf.env.append_value('CXXFLAGS', '-fsanitize=address')
127         conf.env.append_value('LINKFLAGS', '-fsanitize=address')
128
129     if conf.env['CXX_NAME'] == 'gcc':
130         gcc = conf.env['CC_VERSION']
131         if int(gcc[0]) >= 8:
132             # I tried and failed to ignore these with _Pragma
133             conf.env.append_value('CXXFLAGS', ['-Wno-cast-function-type'])
134         # Most gccs still give these warnings from boost::optional
135         conf.env.append_value('CXXFLAGS', ['-Wno-maybe-uninitialized'])
136         if int(gcc[0]) > 4:
137             # gcc 4.8.5 on Centos 7 does not have this warning
138             conf.env.append_value('CXXFLAGS', ['-Wsuggest-override'])
139
140     if conf.options.enable_debug:
141         conf.env.append_value('CXXFLAGS', ['-g', '-DDCPOMATIC_DEBUG', '-fno-omit-frame-pointer'])
142     else:
143         conf.env.append_value('CXXFLAGS', '-O2')
144
145     if conf.options.enable_disk:
146         conf.env.append_value('CXXFLAGS', '-DDCPOMATIC_DISK')
147
148     if conf.options.use_lld:
149         try:
150             conf.find_program('ld.lld')
151             conf.env.append_value('LINKFLAGS', '-fuse-ld=lld')
152         except conf.errors.ConfigurationError:
153             pass
154
155     #
156     # Windows/Linux/macOS specific
157     #
158
159     # Windows
160     if conf.env.TARGET_WINDOWS_64 or conf.env.TARGET_WINDOWS_32:
161         conf.env.append_value('CXXFLAGS', '-DDCPOMATIC_WINDOWS')
162         conf.env.append_value('CXXFLAGS', '-DWIN32_LEAN_AND_MEAN')
163         conf.env.append_value('CXXFLAGS', '-DBOOST_USE_WINDOWS_H')
164         conf.env.append_value('CXXFLAGS', '-DBOOST_THREAD_PROVIDES_GENERIC_SHARED_MUTEX_ON_WIN')
165         conf.env.append_value('CXXFLAGS', '-mfpmath=sse')
166         conf.env.append_value('CXXFLAGS', '-Wcast-align')
167         wxrc = os.popen('wx-config --rescomp').read().split()[1:]
168         conf.env.append_value('WINRCFLAGS', wxrc)
169         if conf.options.enable_debug:
170             conf.env.append_value('CXXFLAGS', ['-mconsole'])
171             conf.env.append_value('LINKFLAGS', ['-mconsole'])
172         conf.check(lib='ws2_32', uselib_store='WINSOCK2', msg="Checking for library winsock2")
173         conf.check(lib='dbghelp', uselib_store='DBGHELP', msg="Checking for library dbghelp")
174         conf.check(lib='shlwapi', uselib_store='SHLWAPI', msg="Checking for library shlwapi")
175         conf.check(lib='mswsock', uselib_store='MSWSOCK', msg="Checking for library mswsock")
176         conf.check(lib='ole32', uselib_store='OLE32', msg="Checking for library ole32")
177         conf.check(lib='dsound', uselib_store='DSOUND', msg="Checking for library dsound")
178         conf.check(lib='winmm', uselib_store='WINMM', msg="Checking for library winmm")
179         conf.check(lib='ksuser', uselib_store='KSUSER', msg="Checking for library ksuser")
180         conf.check(lib='setupapi', uselib_store='SETUPAPI', msg="Checking for library setupapi")
181         conf.check(lib='uuid', uselib_store='UUID', msg="Checking for library uuid")
182         boost_lib_suffix = '-mt-x32' if conf.options.target_windows_32 else '-mt-x64'
183         boost_thread = 'boost_thread' + boost_lib_suffix
184         conf.check_cxx(fragment="""
185                                #include <boost/locale.hpp>\n
186                                int main() { std::locale::global (boost::locale::generator().generate ("")); }\n
187                                """,
188                                msg='Checking for boost locale library',
189                                libpath='/usr/local/lib',
190                                lib=['boost_locale%s' % boost_lib_suffix, 'boost_system%s' % boost_lib_suffix],
191                                uselib_store='BOOST_LOCALE')
192
193     # POSIX
194     if conf.env.TARGET_LINUX or conf.env.TARGET_OSX:
195         conf.env.append_value('CXXFLAGS', '-DDCPOMATIC_POSIX')
196         boost_lib_suffix = ''
197         boost_thread = 'boost_thread'
198         conf.env.append_value('LINKFLAGS', '-pthread')
199
200     # Linux
201     if conf.env.TARGET_LINUX:
202         conf.env.append_value('CXXFLAGS', '-mfpmath=sse')
203         conf.env.append_value('CXXFLAGS', '-DLINUX_LOCALE_PREFIX="%s/share/locale"' % conf.env['INSTALL_PREFIX'])
204         conf.env.append_value('CXXFLAGS', '-DLINUX_SHARE_PREFIX="%s/share"' % conf.env['INSTALL_PREFIX'])
205         conf.env.append_value('CXXFLAGS', '-DDCPOMATIC_LINUX')
206         conf.env.append_value('CXXFLAGS', ['-Wlogical-op', '-Wcast-align'])
207         conf.check(lib='dl', uselib_store='DL', msg='Checking for library dl')
208
209     # OSX
210     if conf.env.TARGET_OSX:
211         conf.env.append_value('CXXFLAGS', ['-DDCPOMATIC_OSX', '-DGL_SILENCE_DEPRECATION'])
212         conf.env.append_value('LINKFLAGS', '-headerpad_max_install_names')
213         conf.env.append_value('LINKFLAGS', '-llzma')
214
215     #
216     # Dependencies.
217     #
218
219     # It should be possible to use check_cfg for both dynamic and static linking, but
220     # e.g. pkg-config --libs --static foo returns some libraries that should be statically
221     # linked and others that should be dynamic.  This doesn't work too well with waf
222     # as it wants them separate.
223
224     # libcurl
225     if conf.options.static_curl:
226         conf.env.STLIB_CURL = ['curl']
227         conf.env.LIB_CURL = ['ssh2', 'idn']
228     else:
229         conf.check_cfg(package='libcurl', args='libcurl >= 7.19.1 --cflags --libs', uselib_store='CURL', mandatory=True)
230
231     # libicu
232     if conf.check_cfg(package='icu-i18n', args='--cflags --libs', uselib_store='ICU', mandatory=False) is None:
233         if conf.check_cfg(package='icu', args='--cflags --libs', uselib_store='ICU', mandatory=False) is None:
234             conf.check_cxx(fragment="""
235                             #include <unicode/ucsdet.h>
236                             int main(void) {
237                                 UErrorCode status = U_ZERO_ERROR;
238                                 UCharsetDetector* detector = ucsdet_open (&status);
239                                 return 0; }\n
240                             """,
241                        mandatory=True,
242                        msg='Checking for libicu',
243                        okmsg='yes',
244                        libpath=['/usr/local/lib', '/usr/lib', '/usr/lib/x86_64-linux-gnu'],
245                        lib=['icuio', 'icui18n', 'icudata', 'icuuc'],
246                        uselib_store='ICU')
247
248     # libsamplerate
249     conf.check_cfg(package='samplerate', args='--cflags --libs', uselib_store='SAMPLERATE', mandatory=True)
250
251     # glib
252     conf.check_cfg(package='glib-2.0', args='--cflags --libs', uselib_store='GLIB', mandatory=True)
253
254     # libzip
255     conf.check_cfg(package='libzip', args='--cflags --libs', uselib_store='ZIP', mandatory=True)
256     conf.check_cxx(fragment="""
257                             #include <zip.h>
258                             int main() { zip_source_t* foo; (void)foo; }
259                             """,
260                    mandatory=False,
261                    msg="Checking for zip_source_t",
262                    uselib="ZIP",
263                    define_name='DCPOMATIC_HAVE_ZIP_SOURCE_T'
264                    )
265     conf.check_cxx(fragment="""
266                             #include <zip.h>
267                             int main() { struct zip* zip = nullptr; zip_source_t* source = nullptr; zip_file_add(zip, "foo", source, ZIP_FL_ENC_GUESS); }
268                             """,
269                    mandatory=False,
270                    msg="Checking for zip_file_add",
271                    uselib="ZIP",
272                    define_name='DCPOMATIC_HAVE_ZIP_FILE_ADD'
273                    )
274
275     # libbz2; must be explicitly linked on macOS for some reason
276     conf.check_cxx(fragment="""
277                             #include <bzlib.h>
278                             int main() { BZ2_bzCompressInit(0, 0, 0, 0); }
279                             """,
280                    mandatory=True,
281                    msg="Checking for libbz2",
282                    okmsg='yes',
283                    lib='bz2',
284                    uselib_store="BZ2"
285                    )
286
287     # libz; must be explicitly linked on macOS for some reason
288     conf.check_cxx(fragment="""
289                             #include <zlib.h>
290                             int main() { zlibVersion(); }
291                             """,
292                    mandatory=True,
293                    msg="Checking for libz",
294                    okmsg='yes',
295                    lib='z',
296                    uselib_store="LIBZ"
297                    )
298
299     # fontconfig
300     conf.check_cfg(package='fontconfig', args='--cflags --libs', uselib_store='FONTCONFIG', mandatory=True)
301
302     # pangomm
303     conf.check_cfg(package='pangomm-1.4', args='--cflags --libs', uselib_store='PANGOMM', mandatory=True)
304
305     # cairomm
306     conf.check_cfg(package='cairomm-1.0', args='--cflags --libs', uselib_store='CAIROMM', mandatory=True)
307
308     # leqm_nrt
309     conf.check_cfg(package='leqm_nrt', args='--cflags --libs', uselib_store='LEQM_NRT', mandatory=True)
310
311     # libcxml
312     if conf.options.static_cxml:
313         conf.check_cfg(package='libcxml', args='libcxml >= 0.17.0 --cflags', uselib_store='CXML', mandatory=True)
314         conf.env.STLIB_CXML = ['cxml']
315     else:
316         conf.check_cfg(package='libcxml', args='libcxml >= 0.16.0 --cflags --libs', uselib_store='CXML', mandatory=True)
317
318     # libssh
319     if conf.options.static_ssh:
320         conf.env.STLIB_SSH = ['ssh']
321         if conf.options.workaround_gssapi:
322             conf.env.LIB_SSH = ['gssapi_krb5']
323     else:
324         conf.check_cxx(fragment="""
325                                #include <libssh/libssh.h>\n
326                                int main () {\n
327                                ssh_new ();\n
328                                return 0;\n
329                                }
330                                """,
331                       msg='Checking for library libssh',
332                       mandatory=True,
333                       lib='ssh',
334                       uselib_store='SSH')
335
336     # libdcp
337     if conf.options.static_dcp:
338         conf.check_cfg(package='libdcp-1.0', args='libdcp-1.0 >= %s --cflags' % libdcp_version, uselib_store='DCP', mandatory=True)
339         conf.env.DEFINES_DCP = [f.replace('\\', '') for f in conf.env.DEFINES_DCP]
340         conf.env.STLIB_DCP = ['dcp-1.0', 'asdcp-carl', 'kumu-carl', 'openjp2']
341         conf.env.LIB_DCP = ['glibmm-2.4', 'ssl', 'crypto', 'bz2', 'xslt', 'xerces-c']
342     else:
343         conf.check_cfg(package='libdcp-1.0', args='libdcp-1.0 >= %s --cflags --libs' % libdcp_version, uselib_store='DCP', mandatory=True)
344         conf.env.DEFINES_DCP = [f.replace('\\', '') for f in conf.env.DEFINES_DCP]
345
346     # libsub
347     if conf.options.static_sub:
348         conf.check_cfg(package='libsub-1.0', args='libsub-1.0 >= %s --cflags' % libsub_version, uselib_store='SUB', mandatory=True)
349         conf.env.DEFINES_SUB = [f.replace('\\', '') for f in conf.env.DEFINES_SUB]
350         conf.env.STLIB_SUB = ['sub-1.0']
351     else:
352         conf.check_cfg(package='libsub-1.0', args='libsub-1.0 >= %s --cflags --libs' % libsub_version, uselib_store='SUB', mandatory=True)
353         conf.env.DEFINES_SUB = [f.replace('\\', '') for f in conf.env.DEFINES_SUB]
354
355     # libxml++
356     if conf.options.static_xmlpp:
357         conf.env.STLIB_XMLPP = ['xml++-2.6']
358         conf.env.LIB_XMLPP = ['xml2']
359     else:
360         conf.check_cfg(package='libxml++-2.6', args='--cflags --libs', uselib_store='XMLPP', mandatory=True)
361
362     # libxmlsec
363     if conf.options.static_xmlsec:
364         if conf.check_cxx(lib='xmlsec1-openssl', mandatory=False):
365             conf.env.STLIB_XMLSEC = ['xmlsec1-openssl', 'xmlsec1']
366         else:
367             conf.env.STLIB_XMLSEC = ['xmlsec1']
368     else:
369         conf.env.LIB_XMLSEC = ['xmlsec1-openssl', 'xmlsec1']
370
371     # nettle
372     conf.check_cfg(package="nettle", args='--cflags --libs', uselib_store='NETTLE', mandatory=True)
373
374     # libpng
375     conf.check_cfg(package='libpng', args='--cflags --libs', uselib_store='PNG', mandatory=True)
376
377     # libjpeg
378     conf.check_cxx(fragment="""
379                             #include <cstddef>
380                             #include <cstdio>
381                             #include <jpeglib.h>
382                             int main() { struct jpeg_compress_struct compress; jpeg_create_compress (&compress); return 0; }
383                             """,
384                    msg='Checking for libjpeg',
385                    libpath='/usr/local/lib',
386                    lib=['jpeg'],
387                    uselib_store='JPEG')
388
389     # lwext4
390     if conf.options.enable_disk:
391         conf.check_cxx(fragment="""
392                                 #include <lwext4/ext4.h>\n
393                                 int main() { ext4_mount("ext4_fs", "/mp/", false); }\n
394                                 """,
395                                 msg='Checking for lwext4 library',
396                                 libpath='/usr/local/lib',
397                                 lib=['lwext4', 'blockdev'],
398                                 uselib_store='LWEXT4')
399
400     if conf.env.TARGET_LINUX and conf.options.enable_disk:
401         conf.check_cfg(package='polkit-gobject-1', args='--cflags --libs', uselib_store='POLKIT', mandatory=True)
402
403     # nanomsg
404     if conf.options.enable_disk:
405         if conf.check_cfg(package='nanomsg', args='--cflags --libs', uselib_store='NANOMSG', mandatory=False) is None:
406             conf.check_cfg(package='libnanomsg', args='--cflags --libs', uselib_store='NANOMSG', mandatory=True)
407         if conf.env.TARGET_LINUX:
408             # We link with nanomsg statically on Centos 8 so we need to link this as well
409             conf.env.LIB_NANOMSG.append('anl')
410
411     # FFmpeg
412     if conf.options.static_ffmpeg:
413         names = ['avformat', 'avfilter', 'avcodec', 'avutil', 'swscale', 'postproc', 'swresample']
414         for name in names:
415             static = subprocess.Popen(shlex.split('pkg-config --static --libs lib%s' % name), stdout=subprocess.PIPE).communicate()[0].decode('utf-8')
416             libs = []
417             stlibs = []
418             include = []
419             libpath = []
420             for s in static.split():
421                 if s.startswith('-L'):
422                     libpath.append(s[2:])
423                 elif s.startswith('-I'):
424                     include.append(s[2:])
425                 elif s.startswith('-l'):
426                     if s[2:] not in names:
427                         libs.append(s[2:])
428                     else:
429                         stlibs.append(s[2:])
430
431             conf.env['LIB_%s' % name.upper()] = libs
432             conf.env['STLIB_%s' % name.upper()] = stlibs
433             conf.env['INCLUDES_%s' % name.upper()] = include
434             conf.env['LIBPATH_%s' % name.upper()] = libpath
435     else:
436         conf.check_cfg(package='libavformat', args='--cflags --libs', uselib_store='AVFORMAT', mandatory=True)
437         conf.check_cfg(package='libavfilter', args='--cflags --libs', uselib_store='AVFILTER', mandatory=True)
438         conf.check_cfg(package='libavcodec', args='--cflags --libs', uselib_store='AVCODEC', mandatory=True)
439         conf.check_cfg(package='libavutil', args='--cflags --libs', uselib_store='AVUTIL', mandatory=True)
440         conf.check_cfg(package='libswscale', args='--cflags --libs', uselib_store='SWSCALE', mandatory=True)
441         conf.check_cfg(package='libpostproc', args='--cflags --libs', uselib_store='POSTPROC', mandatory=True)
442         conf.check_cfg(package='libswresample', args='--cflags --libs', uselib_store='SWRESAMPLE', mandatory=True)
443
444     # Check to see if we have our version of FFmpeg that allows us to get at EBUR128 results
445     conf.check_cxx(fragment="""
446                             extern "C" {\n
447                             #include <libavfilter/f_ebur128.h>\n
448                             }\n
449                             int main () { av_ebur128_get_true_peaks (0); }\n
450                             """,
451                    msg='Checking for EBUR128-patched FFmpeg',
452                    uselib='AVCODEC AVFILTER',
453                    define_name='DCPOMATIC_HAVE_EBUR128_PATCHED_FFMPEG',
454                    mandatory=False)
455
456     # Check to see if we have our AVSubtitleRect has a pict member
457     # Older versions (e.g. that shipped with Ubuntu 16.04) do
458     conf.check_cxx(fragment="""
459                             extern "C" {\n
460                             #include <libavcodec/avcodec.h>\n
461                             }\n
462                             int main () { AVSubtitleRect r; r.pict; }\n
463                             """,
464                    msg='Checking for AVSubtitleRect::pict',
465                    cxxflags='-Wno-unused-result -Wno-unused-value -Wdeprecated-declarations -Werror',
466                    uselib='AVCODEC',
467                    define_name='DCPOMATIC_HAVE_AVSUBTITLERECT_PICT',
468                    mandatory=False)
469
470     # Check to see if we have our AVComponentDescriptor has a depth_minus1 member
471     # Older versions (e.g. that shipped with Ubuntu 16.04) do
472     conf.check_cxx(fragment="""
473                             extern "C" {\n
474                             #include <libavutil/pixdesc.h>\n
475                             }\n
476                             int main () { AVComponentDescriptor d; d.depth_minus1; }\n
477                             """,
478                    msg='Checking for AVComponentDescriptor::depth_minus1',
479                    cxxflags='-Wno-unused-result -Wno-unused-value -Wdeprecated-declarations -Werror',
480                    uselib='AVUTIL',
481                    define_name='DCPOMATIC_HAVE_AVCOMPONENTDESCRIPTOR_DEPTH_MINUS1',
482                    mandatory=False)
483
484     # See if we have av_register_all and avfilter_register_all
485     conf.check_cxx(fragment="""
486                             extern "C" {\n
487                             #include <libavformat/avformat.h>\n
488                             #include <libavfilter/avfilter.h>\n
489                             }\n
490                             int main () { av_register_all(); avfilter_register_all(); }\n
491                             """,
492                    msg='Checking for av_register_all and avfilter_register_all',
493                    uselib='AVFORMAT AVFILTER',
494                    define_name='DCPOMATIC_HAVE_AVREGISTER',
495                    mandatory=False)
496
497     # Hack: the previous two check_cxx calls end up copying their (necessary) cxxflags
498     # to these variables.  We don't want to use these for the actual build, so clean them out.
499     conf.env['CXXFLAGS_AVCODEC'] = []
500     conf.env['CXXFLAGS_AVUTIL'] = []
501
502     if conf.env.TARGET_LINUX:
503         conf.env.LIB_X11 = ['X11']
504
505     # We support older boosts on Linux so we can use the distribution-provided package
506     # on Centos 7, but it's good if we can use 1.61 for boost::dll::program_location()
507     boost_version = ('1.45', '104500') if conf.env.TARGET_LINUX else ('1.61', '106800')
508
509     # Boost
510     if conf.options.static_boost:
511         conf.env.STLIB_BOOST_THREAD = ['boost_thread']
512         conf.env.STLIB_BOOST_FILESYSTEM = ['boost_filesystem%s' % boost_lib_suffix]
513         conf.env.STLIB_BOOST_DATETIME = ['boost_date_time%s' % boost_lib_suffix, 'boost_system%s' % boost_lib_suffix]
514         conf.env.STLIB_BOOST_SIGNALS2 = ['boost_signals2']
515         conf.env.STLIB_BOOST_SYSTEM = ['boost_system']
516         conf.env.STLIB_BOOST_REGEX = ['boost_regex']
517     else:
518         conf.check_cxx(fragment="""
519                             #include <boost/version.hpp>\n
520                             #if BOOST_VERSION < %s\n
521                             #error boost too old\n
522                             #endif\n
523                             int main(void) { return 0; }\n
524                             """ % boost_version[1],
525                        mandatory=True,
526                        msg='Checking for boost library >= %s' % boost_version[0],
527                        okmsg='yes',
528                        errmsg='too old\nPlease install boost version %s or higher.' % boost_version[0])
529
530         conf.check_cxx(fragment="""
531                             #include <boost/thread.hpp>\n
532                             int main() { boost::thread t; }\n
533                             """,
534                        msg='Checking for boost threading library',
535                        libpath='/usr/local/lib',
536                        lib=[boost_thread, 'boost_system%s' % boost_lib_suffix],
537                        uselib_store='BOOST_THREAD')
538
539         conf.check_cxx(fragment="""
540                             #include <boost/filesystem.hpp>\n
541                             int main() { boost::filesystem::copy_file ("a", "b"); }\n
542                             """,
543                        msg='Checking for boost filesystem library',
544                        libpath='/usr/local/lib',
545                        lib=['boost_filesystem%s' % boost_lib_suffix, 'boost_system%s' % boost_lib_suffix],
546                        uselib_store='BOOST_FILESYSTEM')
547
548         conf.check_cxx(fragment="""
549                             #include <boost/date_time.hpp>\n
550                             int main() { boost::gregorian::day_clock::local_day(); }\n
551                             """,
552                        msg='Checking for boost datetime library',
553                        libpath='/usr/local/lib',
554                        lib=['boost_date_time%s' % boost_lib_suffix, 'boost_system%s' % boost_lib_suffix],
555                        uselib_store='BOOST_DATETIME')
556
557         conf.check_cxx(fragment="""
558                             #include <boost/signals2.hpp>\n
559                             int main() { boost::signals2::signal<void (int)> x; }\n
560                             """,
561                        msg='Checking for boost signals2 library',
562                        uselib_store='BOOST_SIGNALS2')
563
564         conf.check_cxx(fragment="""
565                             #include <boost/regex.hpp>\n
566                             int main() { boost::regex re ("foo"); }\n
567                             """,
568                        msg='Checking for boost regex library',
569                        lib=['boost_regex%s' % boost_lib_suffix],
570                        uselib_store='BOOST_REGEX')
571
572         # Really just checking for the header here (there's no associated library) but the test
573         # program has to link with boost_system so I'm doing it this way.
574         if conf.options.enable_disk:
575             deps = ['boost_system%s' % boost_lib_suffix]
576             if conf.env.TARGET_WINDOWS_64 or conf.env.TARGET_WINDOWS_32:
577                 deps.append('ws2_32')
578                 deps.append('boost_filesystem%s' % boost_lib_suffix)
579             conf.check_cxx(fragment="""
580                                 #include <boost/process.hpp>\n
581                                 int main() { new boost::process::child("foo"); }\n
582                                 """,
583                            cxxflags='-Wno-unused-parameter',
584                            msg='Checking for boost process library',
585                            lib=deps,
586                            uselib_store='BOOST_PROCESS')
587
588     # Other stuff
589
590     conf.find_program('msgfmt', var='MSGFMT')
591     conf.check(header_name='valgrind/memcheck.h', mandatory=False)
592
593     datadir = conf.env.DATADIR
594     if not datadir:
595         datadir = os.path.join(conf.env.PREFIX, 'share')
596
597     conf.define('LOCALEDIR', os.path.join(datadir, 'locale'))
598     conf.define('DATADIR', datadir)
599
600     conf.recurse('src')
601     if not conf.env.DISABLE_TESTS:
602         conf.recurse('test')
603
604     Logs.pprint('YELLOW', '')
605     if conf.env.TARGET_WINDOWS_64 or conf.env.TARGET_WINDOWS_32:
606         Logs.pprint('YELLOW', '\t' + 'Target'.ljust(25) + ': Windows')
607     elif conf.env.TARGET_LINUX:
608         Logs.pprint('YELLOW', '\t' + 'Target'.ljust(25) + ': Linux')
609     elif conf.env.TARGET_OSX:
610         Logs.pprint('YELLOW', '\t' + 'Target'.ljust(25) + ': macOS')
611
612     def report(name, variable):
613         linkage = ''
614         if variable:
615             linkage = 'static'
616         else:
617             linkage = 'dynamic'
618         Logs.pprint('YELLOW', '\t%s: %s' % (name.ljust(25), linkage))
619
620     report('DCP-o-matic libraries', conf.options.static_dcpomatic)
621     report('Boost', conf.options.static_boost)
622     report('wxWidgets', conf.options.static_wxwidgets)
623     report('FFmpeg', conf.options.static_ffmpeg)
624     report('libxml++', conf.options.static_xmlpp)
625     report('xmlsec', conf.options.static_xmlsec)
626     report('libssh', conf.options.static_ssh)
627     report('libcxml', conf.options.static_cxml)
628     report('libdcp', conf.options.static_dcp)
629     report('libcurl', conf.options.static_curl)
630
631     Logs.pprint('YELLOW', '')
632
633 def build(bld):
634     create_version_cc(VERSION, bld.env.CXXFLAGS)
635
636     bld.recurse('src')
637     bld.recurse('graphics')
638
639     if not bld.env.DISABLE_TESTS:
640         bld.recurse('test')
641     if bld.env.TARGET_WINDOWS_64 or bld.env.TARGET_WINDOWS_32:
642         bld.recurse('platform/windows')
643     if bld.env.TARGET_LINUX:
644         bld.recurse('platform/linux')
645     if bld.env.TARGET_OSX:
646         bld.recurse('platform/osx')
647
648     if not bld.env.TARGET_WINDOWS_64 and not bld.env.TARGET_WINDOWS_32:
649         bld.install_files('${PREFIX}/share/dcpomatic2', 'fonts/LiberationSans-Regular.ttf')
650         bld.install_files('${PREFIX}/share/dcpomatic2', 'fonts/LiberationSans-Italic.ttf')
651         bld.install_files('${PREFIX}/share/dcpomatic2', 'fonts/LiberationSans-Bold.ttf')
652
653     bld.add_post_fun(post)
654
655 def git_revision():
656     if not os.path.exists('.git'):
657         return None
658
659     cmd = "LANG= git log --abbrev HEAD^..HEAD ."
660     output = subprocess.Popen(cmd, shell=True, stderr=subprocess.STDOUT, stdout=subprocess.PIPE).communicate()[0].splitlines()
661     if len(output) == 0:
662         return None
663     o = output[0].decode('utf-8')
664     return o.replace("commit ", "")[0:10]
665
666 def dist(ctx):
667     r = git_revision()
668     if r is not None:
669         f = open('.git_revision', 'w')
670         print(r, file=f)
671         f.close()
672
673     ctx.excl = """
674                TODO core *~ src/wx/*~ src/lib/*~ builds/*~ doc/manual/*~ src/tools/*~ *.pyc .waf* build .git
675                deps alignment hacks sync *.tar.bz2 *.exe .lock* *build-windows doc/manual/pdf doc/manual/html
676                GRSYMS GRTAGS GSYMS GTAGS compile_commands.json
677                """
678
679 def create_version_cc(version, cxx_flags):
680     commit = git_revision()
681     if commit is None and os.path.exists('.git_revision'):
682         f = open('.git_revision', 'r')
683         commit = f.readline().strip()
684
685     if commit is None:
686         commit = 'release'
687
688     try:
689         text =  '#include "version.h"\n'
690         text += 'char const * dcpomatic_git_commit = \"%s\";\n' % commit
691         text += 'char const * dcpomatic_version = \"%s\";\n' % version
692
693         t = ''
694         for f in cxx_flags:
695             f = f.replace('"', '\\"')
696             t += f + ' '
697         text += 'char const * dcpomatic_cxx_flags = \"%s\";\n' % t[:-1]
698
699         print('Writing version information to src/lib/version.cc')
700         o = open('src/lib/version.cc', 'w')
701         o.write(text)
702         o.close()
703     except IOError:
704         print('Could not open src/lib/version.cc for writing\n')
705         sys.exit(-1)
706
707 def post(ctx):
708     if ctx.cmd == 'install' and ctx.env.TARGET_LINUX:
709         ctx.exec_command('/sbin/ldconfig')
710         exe = os.path.join(ctx.env['INSTALL_PREFIX'], 'bin/dcpomatic2_disk_writer')
711         if os.path.exists(exe):
712             os.system('setcap "cap_dac_override+ep cap_sys_admin+ep" %s' % exe)
713
714 def pot(bld):
715     bld.recurse('src')
716
717 def pot_merge(bld):
718     bld.recurse('src')
719
720 def supporters(bld):
721     r = os.system('curl -m 2 -s -f https://dcpomatic.com/supporters.cc > src/wx/supporters.cc')
722     if (r >> 8) == 0:
723         r = os.system('curl -s -f https://dcpomatic.com/subscribers.cc > src/wx/subscribers.cc')
724     if (r >> 8) != 0:
725         raise Exception("Could not download supporters lists (%d)" % (r >> 8))
726
727 def tags(bld):
728     os.system('etags src/lib/*.cc src/lib/*.h src/wx/*.cc src/wx/*.h src/tools/*.cc')
729
730 def cppcheck(bld):
731     os.system('cppcheck --enable=all --quiet .')