File: features.py

package info (click to toggle)
mixxx 2.2.4~dfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 137,476 kB
  • sloc: cpp: 314,879; xml: 162,191; javascript: 109,044; ansic: 15,855; sh: 13,124; python: 11,528; makefile: 685
file content (1392 lines) | stat: -rw-r--r-- 54,824 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
# -*- coding: utf-8 -*-

import os
from . import util
from .mixxx import Feature
import SCons.Script as SCons
from . import depends

class OpenGLES(Feature):
    def description(self):
        return "OpenGL-ES >= 2.0 support [Experimental]"

    def enabled(self, build):
        build.flags['opengles'] = util.get_flags(build.env, 'opengles', 0)
        return int(build.flags['opengles'])

    def add_options(self, build, vars):
        vars.Add('opengles', 'Set to 1 to enable OpenGL-ES >= 2.0 support [Experimental]', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if build.flags['opengles']:
            build.env.Append(CPPDEFINES='__OPENGLES__')

    def sources(self, build):
        return []

class HSS1394(Feature):
    def description(self):
        return "HSS1394 MIDI device support"

    def enabled(self, build):
        if build.platform_is_windows or build.platform_is_osx:
            build.flags['hss1394'] = util.get_flags(build.env, 'hss1394', 1)
        else:
            build.flags['hss1394'] = util.get_flags(build.env, 'hss1394', 0)
        if int(build.flags['hss1394']):
            return True
        return False

    def add_options(self, build, vars):
        if build.platform_is_windows or build.platform_is_osx:
            vars.Add('hss1394',
                     'Set to 1 to enable HSS1394 MIDI device support.', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if build.platform_is_windows or build.platform_is_osx:
#            if not conf.CheckHeader('HSS1394/HSS1394.h'):  # WTF this gives tons of cmath errors on MSVC
#                raise Exception('Did not find HSS1394 development headers')
            if not conf.CheckLib(['libhss1394', 'hss1394']):
                raise Exception('Did not find HSS1394 development library')

        build.env.Append(CPPDEFINES='__HSS1394__')

        if build.platform_is_windows and build.static_dependencies:
            conf.CheckLib('user32')

    def sources(self, build):
        return ['controllers/midi/hss1394controller.cpp',
                'controllers/midi/hss1394enumerator.cpp']


class HID(Feature):
    INTERNAL_LINK = False
    HIDAPI_INTERNAL_PATH = '#lib/hidapi-0.8.0-rc1'

    def description(self):
        return "HID controller support"

    def enabled(self, build):
        build.flags['hid'] = util.get_flags(build.env, 'hid', 1)
        if int(build.flags['hid']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('hid', 'Set to 1 to enable HID controller support.', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        if build.platform_is_linux:
            # Try using system lib
            if not conf.CheckLib(['hidapi-libusb', 'libhidapi-libusb']):
                # No System Lib found
                self.INTERNAL_LINK = True
                build.env.ParseConfig(
                    'pkg-config libusb-1.0 --silence-errors --cflags --libs')
                if (not conf.CheckLib(['libusb-1.0', 'usb-1.0']) or
                        not conf.CheckHeader('libusb-1.0/libusb.h')):
                    raise Exception(
                           'Did not find the libusb 1.0 development library or its header file')
            else:
                build.env.ParseConfig('pkg-config hidapi-libusb --silence-errors --cflags --libs')


            # Optionally add libpthread and librt. Some distros need this.
            conf.CheckLib(['pthread', 'libpthread'])
            conf.CheckLib(['rt', 'librt'])

            # -pthread tells GCC to do the right thing regardless of system
            build.env.Append(CCFLAGS='-pthread')
            build.env.Append(LINKFLAGS='-pthread')

        else:
            self.INTERNAL_LINK = True
            if build.platform_is_windows and not conf.CheckLib(['setupapi', 'libsetupapi']):
                raise Exception('Did not find the setupapi library, exiting.')
            elif build.platform_is_osx:
                build.env.AppendUnique(FRAMEWORKS=['IOKit', 'CoreFoundation'])

        build.env.Append(CPPDEFINES='__HID__')
        if self.INTERNAL_LINK:
            build.env.Append(
                 CPPPATH=[os.path.join(self.HIDAPI_INTERNAL_PATH, 'hidapi')])

    def sources(self, build):
        sources = ['controllers/hid/hidcontroller.cpp',
                   'controllers/hid/hidenumerator.cpp',
                   'controllers/hid/hidcontrollerpresetfilehandler.cpp']

        if self.INTERNAL_LINK:
            if build.platform_is_windows:
                # Requires setupapi.lib which is included by the above check for
                # setupapi.
                sources.append(
                    os.path.join(self.HIDAPI_INTERNAL_PATH, "windows/hid.c"))
            elif build.platform_is_linux:
                # hidapi compiles the libusb implementation by default on Linux
                sources.append(
                    os.path.join(self.HIDAPI_INTERNAL_PATH, 'libusb/hid.c'))
            elif build.platform_is_osx:
                sources.append(
                    os.path.join(self.HIDAPI_INTERNAL_PATH, 'mac/hid.c'))

        return sources


class Bulk(Feature):
    def description(self):
        return "USB Bulk controller support"

    def enabled(self, build):
        # For now only make Bulk default on Linux only. Turn on for all
        # platforms after the 1.11.0 release.
        is_default = 1 if build.platform_is_linux else 0
        build.flags['bulk'] = util.get_flags(build.env, 'bulk', is_default)
        if int(build.flags['bulk']):
            return True
        return False

    def add_options(self, build, vars):
        is_default = 1 if build.platform_is_linux else 0
        vars.Add('bulk',
                 'Set to 1 to enable USB Bulk controller support.', is_default)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.ParseConfig(
            'pkg-config libusb-1.0 --silence-errors --cflags --libs')
        if (not conf.CheckLib(['libusb-1.0', 'usb-1.0']) or
                not conf.CheckHeader('libusb-1.0/libusb.h')):
            raise Exception(
                'Did not find the libusb 1.0 development library or its header file, exiting!')

        build.env.Append(CPPDEFINES='__BULK__')

    def sources(self, build):
        sources = ['controllers/bulk/bulkcontroller.cpp',
                   'controllers/bulk/bulkenumerator.cpp']
        if not int(build.flags['hid']):
            sources.append(
                'controllers/hid/hidcontrollerpresetfilehandler.cpp')
        return sources


class Mad(Feature):
    def description(self):
        return "MAD MP3 Decoder"

    def default(self, build):
        return 0 if build.platform_is_osx else 1

    def enabled(self, build):
        build.flags['mad'] = util.get_flags(build.env, 'mad',
                                            self.default(build))
        if int(build.flags['mad']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('mad', 'Set to 1 to enable MAD MP3 decoder support.',
                 self.default(build))

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if not conf.CheckLib(['libmad', 'mad']):
            raise Exception(
                'Did not find libmad.a, libmad.lib, or the libmad development header files - exiting!')
        if not conf.CheckLib(['libid3tag', 'id3tag', 'libid3tag-release']):
            raise Exception(
                'Did not find libid3tag.a, libid3tag.lib, or the libid3tag development header files - exiting!')
        build.env.Append(CPPDEFINES='__MAD__')

    def sources(self, build):
        return ['sources/soundsourcemp3.cpp']


class CoreAudio(Feature):

    def description(self):
        return "CoreAudio MP3/AAC Decoder"

    def default(self, build):
        return 1 if build.platform_is_osx else 0

    def enabled(self, build):
        build.flags['coreaudio'] = util.get_flags(
            build.env, 'coreaudio', self.default(build))
        if int(build.flags['coreaudio']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add(
            'coreaudio', 'Set to 1 to enable CoreAudio MP3/AAC decoder support.',
            self.default(build))

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        if not build.platform_is_osx:
            raise Exception('CoreAudio is only supported on OS X!')

        build.env.Append(CPPPATH='#lib/apple/')
        build.env.AppendUnique(FRAMEWORKS=['AudioToolbox', 'CoreFoundation'])
        build.env.Append(CPPDEFINES='__COREAUDIO__')

    def sources(self, build):
        return ['sources/soundsourcecoreaudio.cpp',
                'sources/v1/legacyaudiosourceadapter.cpp',
                '#lib/apple/CAStreamBasicDescription.cpp']


class MediaFoundation(Feature):
    FLAG = 'mediafoundation'

    def description(self):
        return "Media Foundation AAC Decoder Plugin"

    def enabled(self, build):
        build.flags[self.FLAG] = util.get_flags(build.env, self.FLAG, 0)
        if int(build.flags[self.FLAG]):
            return True
        return False

    def add_options(self, build, vars):
        if build.platform_is_windows:
            vars.Add(
                self.FLAG, "Set to 1 to enable the Media Foundation AAC decoder plugin (Windows Vista with KB2117917 or Windows 7 required)", 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if not build.platform_is_windows:
            raise Exception("Media Foundation is only supported on Windows!")
        if not conf.CheckLib('Ole32'):
            raise Exception('Did not find Ole32.lib - exiting!')
        if not conf.CheckLib(['Mfuuid']):
            raise Exception('Did not find Mfuuid.lib - exiting!')
        if not conf.CheckLib(['Mfplat']):
            raise Exception('Did not find Mfplat.lib - exiting!')
        if not conf.CheckLib(['Mfreadwrite']):  # Only available on Windows 7 and up, or properly updated Vista
            raise Exception('Did not find Mfreadwrite.lib - exiting!')
        build.env.Append(CPPDEFINES='__MEDIAFOUNDATION__')


class IPod(Feature):
    def description(self):
        return "NOT-WORKING iPod Support"

    def enabled(self, build):
        build.flags['ipod'] = util.get_flags(build.env, 'ipod', 0)
        if int(build.flags['ipod']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('ipod', 'Set to 1 to enable iPod support through libgpod', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.Append(CPPDEFINES='__IPOD__')
        if build.platform_is_windows:
            build.env.Append(LIBS='gpod')
            # You must check v-this-v directory out from
            # http://publicsvn.songbirdnest.com/vendor-
            # binaries/trunk/windows-i686-msvc8/libgpod/
            build.env.Append(
                LIBPATH='../../../windows-i686-msvc8/libgpod/release/lib')
            # Following building the following must be added to the dist folder in order for mixxx to run with ipod support on Windows
            # \windows-i686-msvc8\libgpod\release\lib\libgpod.dll
            # \windows-i686-msvc8\glib\release\bin\libgobject-2.0-0.dll
            # \windows-i686-msvc8\glib\release\bin\libglib-2.0-0.dll
            # \windows-i686-msvc8\libiconv\release\bin\iconv.dll
            # \windows-i686-msvc8\gettext\release\binintl.dll
        if build.platform_is_linux or build.platform_is_osx:
            # env.Append(LIBS = 'libgpod-1.0')
            # env.Append(LIBS = 'glib-2.0')
            build.env.ParseConfig(
                'pkg-config libgpod-1.0 --silence-errors --cflags --libs')
            build.env.ParseConfig(
                'pkg-config glib-2.0 --silence-errors --cflags --libs')

    def sources(self, build):
        return ['wipodtracksmodel.cpp']


class VinylControl(Feature):
    def description(self):
        return "Vinyl Control"

    def enabled(self, build):
        build.flags['vinylcontrol'] = util.get_flags(build.env,
                                                     'vinylcontrol', 0)
        # Existence of the macappstore option forces vinylcontrol off due to
        # licensing issues.
        if 'macappstore' in build.flags and int(build.flags['macappstore']):
            return False
        if int(build.flags['vinylcontrol']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('vinylcontrol', 'Set to 1 to enable vinyl control support', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        build.env.Append(CPPDEFINES='__VINYLCONTROL__')
        build.env.Append(CPPPATH='#lib/xwax')
        build.env.Append(CPPPATH='#lib/scratchlib')

    def sources(self, build):
        sources = ['vinylcontrol/vinylcontrol.cpp',
                   'vinylcontrol/vinylcontrolxwax.cpp',
                   'preferences/dialog/dlgprefvinyl.cpp',
                   'vinylcontrol/vinylcontrolsignalwidget.cpp',
                   'vinylcontrol/vinylcontrolmanager.cpp',
                   'vinylcontrol/vinylcontrolprocessor.cpp',
                   'vinylcontrol/steadypitch.cpp',
                   'engine/vinylcontrolcontrol.cpp', ]
        if build.platform_is_windows:
            sources.append("#lib/xwax/timecoder_win32.cpp")
            sources.append("#lib/xwax/lut_win32.cpp")
        else:
            sources.append("#lib/xwax/timecoder.c")
            sources.append("#lib/xwax/lut.c")

        return sources


class Vamp(Feature):
    INTERNAL_LINK = False
    INTERNAL_VAMP_PATH = '#lib/vamp'

    def description(self):
        return "Vamp Analyzer support"

    def enabled(self, build):
        build.flags['vamp'] = util.get_flags(build.env, 'vamp', 1)
        if int(build.flags['vamp']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('vamp', 'Set to 1 to enable vamp analysers', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.Append(CPPDEFINES='__VAMP__')
        build.env.Append(CPPDEFINES='kiss_fft_scalar=double')

        # If there is no system vamp-hostsdk is installed or if the version
        # of the installed vamp-hostsdk is less than the bundled version,
        # then we'll directly link the bundled vamp-hostsdk
        if not conf.CheckLib('vamp-hostsdk') or not conf.CheckForPKG('vamp-plugin-sdk', '2.7.1'):
            # For header includes
            build.env.Append(CPPPATH=[self.INTERNAL_VAMP_PATH])
            self.INTERNAL_LINK = True

        # Needed on Linux at least. Maybe needed elsewhere?
        if build.platform_is_linux:
            # Optionally link libdl Required for some distros.
            conf.CheckLib(['dl', 'libdl'])

        # FFTW3 support
        have_fftw3_h = conf.CheckHeader('fftw3.h')
        have_fftw3 = conf.CheckLib('fftw3', autoadd=False)
        if have_fftw3_h and have_fftw3 and build.platform_is_linux:
            build.env.Append(CPPDEFINES='HAVE_FFTW3')
            build.env.ParseConfig(
                'pkg-config fftw3 --silence-errors --cflags --libs')

    def sources(self, build):
        sources = ['analyzer/vamp/vampanalyzer.cpp',
                   'analyzer/vamp/vamppluginadapter.cpp',
                   'analyzer/analyzerbeats.cpp',
                   'analyzer/analyzerkey.cpp',
                   'preferences/dialog/dlgprefbeats.cpp',
                   'preferences/dialog/dlgprefkey.cpp']

        if self.INTERNAL_LINK:
            hostsdk_src_path = '%s/src/vamp-hostsdk' % self.INTERNAL_VAMP_PATH
            sources.extend(path % hostsdk_src_path for path in
                           ['%s/Files.cpp',
                            '%s/PluginBufferingAdapter.cpp',
                            '%s/PluginChannelAdapter.cpp',
                            '%s/PluginHostAdapter.cpp',
                            '%s/PluginInputDomainAdapter.cpp',
                            '%s/PluginLoader.cpp',
                            '%s/PluginSummarisingAdapter.cpp',
                            '%s/PluginWrapper.cpp',
                            '%s/RealTime.cpp'])
        return sources


class ModPlug(Feature):
    def description(self):
        return "Modplug module decoder plugin"

    def enabled(self, build):
        # Default to enabled on but only throw an error if it was explicitly
        # requested and is not available.
        if 'modplug' in build.flags:
            return int(build.flags['modplug']) > 0
        build.flags['modplug'] = util.get_flags(build.env, 'modplug', 1)
        if int(build.flags['modplug']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('modplug',
                 'Set to 1 to enable libmodplug based module tracker support.',
                 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        # Only block the configure if modplug was explicitly requested.
        explicit = 'modplug' in SCons.ARGUMENTS

        if not conf.CheckHeader('libmodplug/modplug.h'):
            if explicit:
                raise Exception('Could not find libmodplug development headers.')
            else:
                build.flags['modplug'] = 0
            return

        if not conf.CheckLib(['modplug', 'libmodplug'], autoadd=True):
            if explicit:
                raise Exception('Could not find libmodplug shared library.')
            else:
                build.flags['modplug'] = 0
            return

        build.env.Append(CPPDEFINES='__MODPLUG__')

    def sources(self, build):
        depends.Qt.uic(build)('preferences/dialog/dlgprefmodplugdlg.ui')
        return ['sources/soundsourcemodplug.cpp', 'preferences/dialog/dlgprefmodplug.cpp']


class FAAD(Feature):
    def description(self):
        return "FAAD AAC audio file decoder plugin"

    def enabled(self, build):
        build.flags['faad'] = util.get_flags(build.env, 'faad', 0)
        if int(build.flags['faad']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('faad',
                 'Set to 1 to enable building the FAAD AAC decoder plugin.', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        have_mp4v2_h = conf.CheckHeader('mp4v2/mp4v2.h')
        have_mp4v2 = conf.CheckLib(['mp4v2', 'libmp4v2'], autoadd=False)
        have_mp4_h = conf.CheckHeader('mp4.h')
        have_mp4 = conf.CheckLib('mp4', autoadd=False)

        # Either mp4 or mp4v2 works
        have_mp4 = (have_mp4v2_h or have_mp4_h) and (have_mp4v2 or have_mp4)

        if not have_mp4:
            raise Exception(
                'Could not find libmp4, libmp4v2 or the libmp4v2 development headers.')

        have_faad = conf.CheckLib(['faad', 'libfaad'], autoadd=False)

        if not have_faad:
            raise Exception(
                'Could not find libfaad or the libfaad development headers.')


class WavPack(Feature):
    def description(self):
        return "WavPack audio file support plugin"

    def enabled(self, build):
        build.flags['wv'] = util.get_flags(build.env, 'wv', 0)
        if int(build.flags['wv']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('wv',
                 'Set to 1 to enable building the WavPack support plugin.', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        have_wv = conf.CheckLib(['wavpack', 'wv'], autoadd=True)
        if not have_wv:
            raise Exception(
                'Could not find libwavpack, libwv or its development headers.')


class ColorDiagnostics(Feature):
    def description(self):
        return "Color Diagnostics"

    def enabled(self, build):
        build.flags['color'] = util.get_flags(build.env, 'color', 0)
        return bool(int(build.flags['color']))

    def add_options(self, build, vars):
        vars.Add('color', "Set to 1 to enable Clang color diagnostics.", 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        if not build.compiler_is_clang:
            raise Exception('Color diagnostics are only available using clang.')

        build.env.Append(CCFLAGS='-fcolor-diagnostics')


class Sanitizers(Feature):
    # Known sanitizers, their names, and their -fsanitize=foo argument.
    SANITIZERS = [('asan', 'AddressSanitizer', 'address'),
                  ('ubsan', 'UndefinedBehaviorSanitizer', 'undefined'),
                  ('tsan', 'ThreadSanitizer', 'thread')]
    def description(self):
        return "Clang Sanitizers (asan, ubsan, tsan, etc.)"

    def enabled(self, build):
        any_enabled = False
        for keyword, _, _ in Sanitizers.SANITIZERS:
            build.flags[keyword] = util.get_flags(build.env, keyword, 0)
            any_enabled = any_enabled or bool(int(build.flags[keyword]))
        return any_enabled

    def add_options(self, build, vars):
        for keyword, name, _ in Sanitizers.SANITIZERS:
            vars.Add(keyword, "Set to 1 to enable the Clang %s." % name, 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        if not build.compiler_is_clang:
            raise Exception('Sanitizers are only available when using clang.')

        sanitizers = []
        for keyword, _, fsanitize in Sanitizers.SANITIZERS:
            if bool(int(build.flags[keyword])):
                sanitizers.append(fsanitize)

        # The Optimize feature below checks whether we are enabled and prevents
        # -fomit-frame-pointer if any sanitizer is enabled.
        build.env.Append(CCFLAGS="-fsanitize=%s" % ','.join(sanitizers))
        build.env.Append(LINKFLAGS="-fsanitize=%s" % ','.join(sanitizers))


class PerfTools(Feature):
    def description(self):
        return "Google PerfTools"

    def enabled(self, build):
        build.flags['perftools'] = util.get_flags(build.env, 'perftools', 0)
        build.flags['perftools_profiler'] = util.get_flags(
            build.env, 'perftools_profiler', 0)
        if int(build.flags['perftools']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add(
            "perftools", "Set to 1 to enable linking against libtcmalloc and Google's performance tools. You must install libtcmalloc from google-perftools to use this option.", 0)
        vars.Add("perftools_profiler", "Set to 1 to enable linking against libprofiler, Google's CPU profiler. You must install libprofiler from google-perftools to use this option.", 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.Append(LIBS="tcmalloc")

        if int(build.flags['perftools_profiler']):
            build.env.Append(LIBS="profiler")


class AsmLib(Feature):
    def description(self):
        return "Agner Fog\'s ASMLIB"

    def enabled(self, build):
        if build.build_is_debug:
            return False
        build.flags['asmlib'] = util.get_flags(build.env, 'asmlib', 0)
        if int(build.flags['asmlib']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add(
            'asmlib', 'Set to 1 to enable linking against Agner Fog\'s hand-optimized asmlib, found at http://www.agner.org/optimize/', 0)

    def configure(self, build, conf):
        if build.build_is_debug:
            self.status = "Disabled (due to debug build)"
            return
        if not self.enabled(build):
            return

        build.env.Append(LIBPATH='#/../asmlib')
        if build.platform_is_linux:
            #Use ASMLIB's functions instead of the compiler's
            build.env.Append(CCFLAGS='-fno-builtin')
            build.env.Prepend(LIBS='":libaelf%so.a"' % build.bitwidth)
        elif build.platform_is_osx:
            #Use ASMLIB's functions instead of the compiler's
            build.env.Append(CCFLAGS='-fno-builtin')
            build.env.Prepend(LIBS='":libamac%so.a"' % build.bitwidth)
        elif build.platform_is_windows:
            #Use ASMLIB's functions instead of the compiler's
            build.env.Append(CCFLAGS='/Oi-')
            build.env.Prepend(LIBS='libacof%so' % build.bitwidth)


class BuildTime(Feature):
    def description(self):
        return "Use __DATE__ and __TIME__"

    def enabled(self, build):
        build.flags['buildtime'] = util.get_flags(build.env, 'buildtime', 1)
        if int(build.flags['buildtime']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add(
            'buildtime', 'Set to 0 to disable build time (__DATE__ and __TIME__) usage.', 1)

    def configure(self, build, conf):
        # Distributions like openSUSE use tools (e. g. build-compare) to detect
        # whether a built binary differs from a former build to avoid unneeded
        # publishing of packages.
        # If __DATE__ and __TIME__ are used the built binary differs always but
        # the tools cannot detect the root and publish a new package although
        # the only change is caused by __DATE__ and __TIME__.
        # So let distributions disable __DATE__ and __TIME__ via buildtime=0.
        if not self.enabled(build):
            build.env.Append(CPPDEFINES='DISABLE_BUILDTIME')


class Verbose(Feature):
    def description(self):
        return "Verbose compilation output"

    def enabled(self, build):
        build.flags['verbose'] = util.get_flags(build.env, 'verbose', 1)
        if int(build.flags['verbose']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('verbose', 'Compile files verbosely.', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            build.env['CCCOMSTR'] = '[CC] $SOURCE'
            build.env['CXXCOMSTR'] = '[CXX] $SOURCE'
            build.env['ASCOMSTR'] = '[AS] $SOURCE'
            build.env['ARCOMSTR'] = '[AR] $TARGET'
            build.env['RANLIBCOMSTR'] = '[RANLIB] $TARGET'
            build.env['LDMODULECOMSTR'] = '[LD] $TARGET'
            build.env['LINKCOMSTR'] = '[LD] $TARGET'

            build.env['QT4_LUPDATECOMSTR'] = '[LUPDATE] $SOURCE'
            build.env['QT4_LRELEASECOMSTR'] = '[LRELEASE] $SOURCE'
            build.env['QT4_QRCCOMSTR'] = '[QRC] $SOURCE'
            build.env['QT4_UICCOMSTR'] = '[UIC4] $SOURCE'
            build.env['QT4_MOCFROMHCOMSTR'] = '[MOC] $SOURCE'
            build.env['QT4_MOCFROMCXXCOMSTR'] = '[MOC] $SOURCE'

            build.env['QT5_LUPDATECOMSTR'] = '[LUPDATE] $SOURCE'
            build.env['QT5_LRELEASECOMSTR'] = '[LRELEASE] $SOURCE'
            build.env['QT5_QRCCOMSTR'] = '[QRC] $SOURCE'
            build.env['QT5_UICCOMSTR'] = '[UIC5] $SOURCE'
            build.env['QT5_MOCCOMSTR'] = '[MOC] $SOURCE'


class Profiling(Feature):
    def description(self):
        return "profiling (e.g. gprof) support"

    def enabled(self, build):
        build.flags['profiling'] = util.get_flags(build.env, 'profiling', 0)
        if int(build.flags['profiling']):
            if build.platform_is_linux or build.platform_is_osx or build.platform_is_bsd:
                return True
        return False

    def add_options(self, build, vars):
        if not build.platform_is_windows:
            vars.Add('profiling',
                     '(DEVELOPER) Set to 1 to enable profiling using gprof (Linux). Disables -fomit-frame-pointer.', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if build.platform_is_linux or build.platform_is_bsd:
            build.env.Append(CCFLAGS='-pg')
            build.env.Append(LINKFLAGS='-pg')


class TestSuite(Feature):
    def description(self):
        return "Mixxx Test Suite"

    def enabled(self, build):
        build.flags['test'] = util.get_flags(build.env, 'test', 0) or \
            'test' in SCons.BUILD_TARGETS
        if int(build.flags['test']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('test', 'Set to 1 to build Mixxx test fixtures.', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

    def sources(self, build):
        # Build the gtest library, but don't return any sources.

        # Clone our main environment so we don't change any settings in the
        # Mixxx environment
        test_env = build.env.Clone()

        # -pthread tells GCC to do the right thing regardless of system
        if build.toolchain_is_gnu:
            test_env.Append(CCFLAGS='-pthread')
            test_env.Append(LINKFLAGS='-pthread')

        test_env.Append(CPPPATH="#lib/gtest-1.7.0/include")
        gtest_dir = test_env.Dir("#lib/gtest-1.7.0")
        # gtest_dir.addRepository(build.env.Dir('#lib/gtest-1.5.0'))
        # build.env['EXE_OUTPUT'] = '#/lib/gtest-1.3.0/bin'  # example,
        # optional
        test_env['LIB_OUTPUT'] = '#/lib/gtest-1.7.0/lib'

        env = test_env
        SCons.Export('env')
        SCons.Export('build')
        env.SConscript(env.File('SConscript', gtest_dir))

        # build and configure gmock
        test_env.Append(CPPPATH="#lib/gmock-1.7.0/include")
        gmock_dir = test_env.Dir("#lib/gmock-1.7.0")
        # gmock_dir.addRepository(build.env.Dir('#lib/gmock-1.5.0'))
        test_env['LIB_OUTPUT'] = '#/lib/gmock-1.7.0/lib'

        env.SConscript(env.File('SConscript', gmock_dir))

        # Build the benchmark library
        test_env.Append(CPPPATH="#lib/benchmark/include")
        benchmark_dir = test_env.Dir("#lib/benchmark")
        test_env['LIB_OUTPUT'] = '#/lib/benchmark/lib'
        env.SConscript(env.File('SConscript', benchmark_dir))

        return []


class LiveBroadcasting(Feature):
    INTERNAL_LINK = False

    def description(self):
        return "Live Broadcasting Support"

    def enabled(self, build):
        build.flags['shoutcast'] = util.get_flags(build.env, 'shoutcast', 1)
        if int(build.flags['shoutcast']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('shoutcast', 'Set to 1 to enable live broadcasting support', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.Append(CPPDEFINES='__BROADCAST__')

        if build.platform_is_linux:
            # Check if system lib is lower at least 2.4.4 and not suffering bug
            # https://bugs.launchpad.net/mixxx/+bug/1833225
            if not conf.CheckForPKG('shout', '2.4.3'):
                self.INTERNAL_LINK = True
 
        if not self.INTERNAL_LINK:
            self.INTERNAL_LINK = not conf.CheckLib(['libshout', 'shout'])

        if self.INTERNAL_LINK:
            print("Using internal shout_mixxx from lib/libshout")
            build.env.Append(CPPPATH='include')
            build.env.Append(CPPPATH='src')
            return

        if build.platform_is_windows and build.static_dependencies:
            conf.CheckLib('winmm')
            conf.CheckLib('ws2_32')
            conf.CheckLib('gdi32')

    def sources(self, build):
        if self.INTERNAL_LINK:
            # Clone our main environment so we don't change any settings in the
            # Mixxx environment
            libshout_env = build.env.Clone()
            libshout_env['LIB_OUTPUT'] = '#lib/libshout/lib'

            if build.toolchain_is_gnu:
                libshout_env.Append(CCFLAGS='-pthread')
                libshout_env.Append(LINKFLAGS='-pthread')

            libshout_env.Append(CPPPATH="#lib/libshout")
            libshout_dir = libshout_env.Dir("#lib/libshout")

            env = libshout_env
            SCons.Export('env')
            SCons.Export('build')
            env.SConscript(
                env.File('SConscript', libshout_dir),
                variant_dir="lib/libshout2",
                duplicate=0,
                exports=['build'])

            build.env.Append(CPPPATH="#lib/libshout/include")
            build.env.Append(LIBPATH='#lib/libshout/lib')
            build.env.Append(LIBS=['shout_mixxx', 'ogg', 'vorbis', 'theora', 'speex', 'ssl', 'crypto'])

        depends.Qt.uic(build)('preferences/dialog/dlgprefbroadcastdlg.ui')
        return ['preferences/dialog/dlgprefbroadcast.cpp',
                'broadcast/broadcastmanager.cpp',
                'engine/sidechain/shoutconnection.cpp']


class Opus(Feature):
    def description(self):
        return "Opus (RFC 6716) support"

    def enabled(self, build):
        # Default Opus to on but only throw an error if it was explicitly
        # requested.
        if 'opus' in build.flags:
            return int(build.flags['opus']) > 0
        build.flags['opus'] = util.get_flags(build.env, 'opus', 1)
        if int(build.flags['opus']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('opus', 'Set to 1 to enable Opus (RFC 6716) support \
                           (supported are Opus 1.0 and above and Opusfile 0.2 and above)', 1)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        # Only block the configure if opus was explicitly requested.
        explicit = 'opus' in SCons.ARGUMENTS

        # Support for Opus (RFC 6716)
        # More info http://http://www.opus-codec.org/
        if not conf.CheckLib(['opusfile', 'libopusfile']):
            if explicit:
                raise Exception('Could not find libopusfile.')
            else:
                build.flags['opus'] = 0
            return

        build.env.Append(CPPDEFINES='__OPUS__')

        if build.platform_is_linux or build.platform_is_bsd:
            build.env.ParseConfig('pkg-config opusfile opus --silence-errors --cflags --libs')

    def sources(self, build):
        return ['sources/soundsourceopus.cpp']


class FFMPEG(Feature):
    def description(self):
        return "FFmpeg/Avconv support"

    def enabled(self, build):
        build.flags['ffmpeg'] = util.get_flags(build.env, 'ffmpeg', 0)
        if int(build.flags['ffmpeg']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('ffmpeg', 'Set to 1 to enable FFmpeg/Avconv support \
                           (supported FFmpeg 0.11-2.x and Avconv 0.8.x-11.x)', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        # Supported version are FFmpeg 0.11-2.x and Avconv 0.8.x-11.x
        # FFmpeg is multimedia library that can be found http://ffmpeg.org/
        # Avconv is fork of FFmpeg that is used mainly in Debian and Ubuntu
        # that can be found http://libav.org
        if build.platform_is_linux or build.platform_is_osx \
                or build.platform_is_bsd:
            # Check for libavcodec, libavformat
            # I just randomly picked version numbers lower than mine for this
            if not conf.CheckForPKG('libavcodec', '53.35.0'):
                raise Exception('Missing libavcodec or it\'s too old! It can'
                                'be separated from main package so check your'
                                'operating system packages.')
            if not conf.CheckForPKG('libavformat', '53.21.0'):
                raise Exception('Missing libavformat  or it\'s too old!'
                                'It can be separated from main package so'
                                'check your operating system packages.')

            # Needed to build new FFmpeg
            build.env.Append(CCFLAGS='-D__STDC_CONSTANT_MACROS')
            build.env.Append(CCFLAGS='-D__STDC_LIMIT_MACROS')
            build.env.Append(CCFLAGS='-D__STDC_FORMAT_MACROS')

            # Grabs the libs and cflags for FFmpeg
            build.env.ParseConfig('pkg-config libavcodec --silence-errors \
                                  --cflags --libs')
            build.env.ParseConfig('pkg-config libavformat --silence-errors \
                                   --cflags --libs')
            build.env.ParseConfig('pkg-config libavutil --silence-errors \
                                   --cflags --libs')

            build.env.Append(CPPDEFINES='__FFMPEGFILE__')
            self.status = "Enabled"

        else:
            # aptitude install libavcodec-dev libavformat-dev liba52-0.7.4-dev
            # libdts-dev
            # Append some stuff to CFLAGS in Windows also
            build.env.Append(CCFLAGS='-D__STDC_CONSTANT_MACROS')
            build.env.Append(CCFLAGS='-D__STDC_LIMIT_MACROS')
            build.env.Append(CCFLAGS='-D__STDC_FORMAT_MACROS')

            build.env.Append(LIBS='avcodec')
            build.env.Append(LIBS='avformat')
            build.env.Append(LIBS='avutil')
            build.env.Append(LIBS='z')
            build.env.Append(LIBS='swresample')
            # build.env.Append(LIBS = 'a52')
            # build.env.Append(LIBS = 'dts')
            build.env.Append(LIBS='gsm')
            # build.env.Append(LIBS = 'dc1394_control')
            # build.env.Append(LIBS = 'dl')
            build.env.Append(LIBS='vorbisenc')
            # build.env.Append(LIBS = 'raw1394')
            build.env.Append(LIBS='vorbis')
            build.env.Append(LIBS='m')
            build.env.Append(LIBS='ogg')
            build.env.Append(CPPDEFINES='__FFMPEGFILE__')

        # Add new path for FFmpeg header files.
        # Non-crosscompiled builds need this too, don't they?
        if build.crosscompile and build.platform_is_windows \
                and build.toolchain_is_gnu:
            build.env.Append(CPPPATH=os.path.join(build.crosscompile_root,
                                                  'include', 'ffmpeg'))

    def sources(self, build):
        return ['sources/soundsourceffmpeg.cpp',
                'encoder/encoderffmpegresample.cpp',
                'encoder/encoderffmpegcore.cpp',
                'encoder/encoderffmpegmp3.cpp',
                'encoder/encoderffmpegvorbis.cpp']


class Optimize(Feature):
    LEVEL_OFF = 'off'
    LEVEL_PORTABLE = 'portable'
    LEVEL_NATIVE = 'native'
    LEVEL_LEGACY = 'legacy'
    LEVEL_FASTBUILD = 'fastbuild'
    LEVEL_DEFAULT = LEVEL_PORTABLE

    def description(self):
        return "Optimization and Tuning"

    @staticmethod
    def get_optimization_level(build):
        optimize_level = build.env.get('optimize', None)
        if optimize_level is None:
            optimize_level = SCons.ARGUMENTS.get('optimize',
                                                 Optimize.LEVEL_DEFAULT)

        try:
            optimize_integer = int(optimize_level)
            if optimize_integer == 0:
                optimize_level = Optimize.LEVEL_OFF
            elif optimize_integer == 1:
                # Level 1 was a legacy (compiler optimizations only) build.
                optimize_level = Optimize.LEVEL_LEGACY
            elif optimize_integer in xrange(2, 10):
                # Levels 2 through 9 map to portable.
                optimize_level = Optimize.LEVEL_PORTABLE
        except:
            pass

        # Support common aliases for off.
        if optimize_level in ('none', 'disable', 'disabled'):
            optimize_level = Optimize.LEVEL_OFF

        if optimize_level not in (Optimize.LEVEL_OFF, Optimize.LEVEL_PORTABLE,
                                  Optimize.LEVEL_NATIVE, Optimize.LEVEL_LEGACY,
                                  Optimize.LEVEL_FASTBUILD):
            raise Exception("optimize={} is not supported. "
                            "Use portable, native, legacy or off"
                            .format(optimize_level))
        return optimize_level

    def enabled(self, build):
        build.flags['optimize'] = Optimize.get_optimization_level(build)
        return build.flags['optimize'] != Optimize.LEVEL_OFF

    def add_options(self, build, vars):
        vars.Add(
            'optimize', 'Set to:\n' \
                        '  portable: sse2 CPU (>= Pentium 4)\n' \
                        '  fastbuild: portable, but without costly optimization steps\n' \
                        '  native: optimized for the CPU of this system\n' \
                        '  legacy: pure i386 code' \
                        '  off: no optimization' \
                        , Optimize.LEVEL_DEFAULT)

    def build_status(self, level, text=None):
        if text is None:
            return level
        return '%s: %s' % (level, text)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        optimize_level = build.flags['optimize']

        if optimize_level == Optimize.LEVEL_OFF:
            self.status = self.build_status(optimize_level, "no optimization")
            return

        if build.toolchain_is_msvs:
            fastbuild_enabled = optimize_level == Optimize.LEVEL_FASTBUILD

            # /GL : http://msdn.microsoft.com/en-us/library/0zza0de8.aspx
            # !!! /GL is incompatible with /ZI, which is set by mscvdebug
            build.env.Append(CCFLAGS='/GL-' if fastbuild_enabled else '/GL')

            # Use the fastest floating point math library
            # http://msdn.microsoft.com/en-us/library/e7s85ffb.aspx
            # http://msdn.microsoft.com/en-us/library/ms235601.aspx
            build.env.Append(CCFLAGS='/fp:fast')

            # Do link-time code generation (and don't show a progress indicator
            # -- this relies on ANSI control characters and tends to overwhelm
            # Jenkins logs) Should we turn on PGO ?
            # http://msdn.microsoft.com/en-us/library/xbf3tbeh.aspx
            build.env.Append(LINKFLAGS='/LTCG:OFF' if fastbuild_enabled else '/LTCG:NOSTATUS')

            # Suggested for unused code removal
            # http://msdn.microsoft.com/en-us/library/ms235601.aspx
            # http://msdn.microsoft.com/en-us/library/xsa71f43.aspx
            # http://msdn.microsoft.com/en-us/library/bxwfs976.aspx
            build.env.Append(CCFLAGS='/Gy')
            build.env.Append(LINKFLAGS='/OPT:REF')
            build.env.Append(LINKFLAGS='/OPT:ICF')

            # Don't worry about aligning code on 4KB boundaries
            # build.env.Append(LINKFLAGS = '/OPT:NOWIN98')
            # ALBERT: NOWIN98 is not supported in MSVC 2010.

            # http://msdn.microsoft.com/en-us/library/59a3b321.aspx
            # In general, you should pick /O2 over /Ox
            build.env.Append(CCFLAGS='/O2')

            if optimize_level == Optimize.LEVEL_PORTABLE or fastbuild_enabled:
                # fastbuild/portable-binary: sse2 CPU (>= Pentium 4)
                self.status = self.build_status(optimize_level,
                                                "sse2 CPU (>= Pentium 4)")
                # SSE and SSE2 are core instructions on x64
                # and consequently raise a warning message from compiler with this flag on x64.
                if not build.machine_is_64bit:
                    build.env.Append(CCFLAGS='/arch:SSE2')
                build.env.Append(CPPDEFINES=['__SSE__', '__SSE2__'])
            elif optimize_level == Optimize.LEVEL_NATIVE:
                self.status = self.build_status(
                    optimize_level, "tuned for this CPU (%s)" % build.machine)
                build.env.Append(CCFLAGS='/favor:' + build.machine)
            elif optimize_level == Optimize.LEVEL_LEGACY:
                self.status = self.build_status(optimize_level,
                                                "pure i386 code")
            else:
                # Not possible to reach this code if enabled is written
                # correctly.
                raise Exception("optimize={} is not supported. "
                                "Use portable, native, legacy or off"
                                .format(optimize_level))

            # SSE and SSE2 are core instructions on x64
            if build.machine_is_64bit:
                build.env.Append(CPPDEFINES=['__SSE__', '__SSE2__'])

        elif build.toolchain_is_gnu:
            # Portable is fast enough on GNU.
            if optimize_level == Optimize.LEVEL_FASTBUILD:
                optimize_level = Optimize.LEVEL_PORTABLE

            # Common flags to all optimizations.
            # -ffast-math will prevent a performance penalty by denormals
            # (floating point values almost Zero are treated as Zero)
            # unfortunately that work only on 64 bit CPUs or with sse2 enabled

            # the following optimisation flags makes the engine code ~3 times
            # faster, measured on a Atom CPU.
            build.env.Append(CCFLAGS='-O3')
            build.env.Append(CCFLAGS='-ffast-math')
            build.env.Append(CCFLAGS='-funroll-loops')

            # set -fomit-frame-pointer when we don't profile and are not using
            # Clang sanitizers.
            # Note: It is only included in -O on machines where it does not
            # interfere with debugging
            if not int(build.flags['profiling']) and not Sanitizers().enabled(build):
                build.env.Append(CCFLAGS='-fomit-frame-pointer')

            if optimize_level == Optimize.LEVEL_PORTABLE:
                # portable: sse2 CPU (>= Pentium 4)
                if build.architecture_is_x86:
                    self.status = self.build_status(optimize_level,
                                                    "sse2 CPU (>= Pentium 4)")
                    build.env.Append(CCFLAGS='-mtune=generic')
                    # -mtune=generic pick the most common, but compatible options.
                    # on arm platforms equivalent to -march=arch
                    if not build.machine_is_64bit:
                        # the sse flags are not set by default on 32 bit builds
                        # but are not supported on arm builds
                        #build.env.Append(CCFLAGS='-msse2')
                        build.env.Append(CCFLAGS='-mfpmath=sse')
                elif build.architecture_is_arm:
                    self.status = self.build_status(optimize_level)
                    #build.env.Append(CCFLAGS='-mfloat-abi=hard')
                    #build.env.Append(CCFLAGS='-mfpu=neon')
                else:
                    self.status = self.build_status(optimize_level)
                # this sets macros __SSE2_MATH__ __SSE_MATH__ __SSE2__ __SSE__
                # This should be our default build for distribution
                # It's a little sketchy, but turning on SSE2 will gain
                # 100% performance in our filter code and allows us to
                # turns on denormal zeroing.
                # We don't really support CPU's earlier than Pentium 4,
                # which is the class of CPUs this decision affects.
                # The downside of this is that we aren't truly
                # i386 compatible, so builds that claim 'i386' will crash.
                # -- rryan 2/2011
                # Note: SSE2 is a core part of x64 CPUs
            elif optimize_level == Optimize.LEVEL_NATIVE:
                self.status = self.build_status(
                    optimize_level, "tuned for this CPU (%s)" % build.machine)
                build.env.Append(CCFLAGS='-march=native')
                # http://en.chys.info/2010/04/what-exactly-marchnative-means/
                # Note: requires gcc >= 4.2.0
                # macros like __SSE2_MATH__ __SSE_MATH__ __SSE2__ __SSE__
                # are set automatically
                if build.architecture_is_x86 and not build.machine_is_64bit:
                    # For 32 bit builds using gcc < 5.0, the mfpmath=sse is
                    # not set by default (not supported on arm builds)
                    # If -msse is not implicitly set, it falls back to mfpmath=387
                    # and a compiler warning is issued (tested with gcc 4.8.4)
                    build.env.Append(CCFLAGS='-mfpmath=sse')
                elif build.architecture_is_arm:
                    self.status = self.build_status(optimize_level)
                    build.env.Append(CCFLAGS='-mfloat-abi=hard')
                    build.env.Append(CCFLAGS='-mfpu=neon')
            elif optimize_level == Optimize.LEVEL_LEGACY:
                if build.architecture_is_x86:
                    self.status = self.build_status(
                        optimize_level, "pure i386 code")
                    build.env.Append(CCFLAGS='-mtune=generic')
                    # -mtune=generic pick the most common, but compatible options.
                    # on arm platforms equivalent to -march=arch
                else:
                    self.status = self.build_status(optimize_level)
            else:
                # Not possible to reach this code if enabled is written
                # correctly.
                raise Exception("optimize={} is not supported. "
                                "Use portable, native, fastbuild, legacy or off"
                                .format(optimize_level))

            # what others do:
            # soundtouch uses just -O3 and -msse in Ubuntu Trusty
            # rubberband uses just -O2 in Ubuntu Trusty
            # fftw3 (used by rubberband) in Ubuntu Trusty
            # -O3 -fomit-frame-pointer -mtune=native -malign-double
            # -fstrict-aliasing -fno-schedule-insns -ffast-math


class MacAppStoreException(Feature):
    def description(self):
        return "Build for Mac App Store"

    def enabled(self, build):
        build.flags['macappstore'] = util.get_flags(build.env,
                                                    'macappstore', 0)
        if int(build.flags['macappstore']):
            # Existence of the macappstore option forces vinylcontrol off due to
            # licensing issues.
            build.flags['vinylcontrol'] = 0
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('macappstore', 'Set to 1 to indicate the build is for the Mac App Store', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        build.env.Append(CPPDEFINES='__MACAPPSTORE__')

class LocaleCompare(Feature):
    def description(self):
        return "Locale Aware Compare for SQLite"

    def default(self, build):
        return 1 if build.platform_is_linux else 0

    def enabled(self, build):
        build.flags['localecompare'] = util.get_flags(build.env, 'localecompare',
                                                      self.default(build))
        if int(build.flags['localecompare']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('localecompare',
                 'Set to 1 to enable Locale Aware Compare support for SQLite.',
                 self.default(build))

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        if int(util.get_flags(build.env, 'qt_sqlite_plugin', 0)):
            raise Exception('WARNING: localecompare is not compatible with the Qt SQLite plugin')
        if not conf.CheckLib(['sqlite3']):
            raise Exception('Missing libsqlite3 -- exiting!')
        build.env.Append(CPPDEFINES='__SQLITE3__')

class Lilv(Feature):
    def description(self):
        return "Lilv library for LV2 support"

    def enabled(self, build):
        build.flags['lilv'] = util.get_flags(build.env, 'lilv', 0)
        if int(build.flags['lilv']):
            return True
        return False

    def add_options(self, build, vars):
        default = 1
        # We do not have lilv set up in the Windows build server environment (yet)
        if build.platform_is_windows:
            default = 0
        vars.Add('lilv', 'Set to 1 to enable Lilv library for LV2 support', default)

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        if build.platform_is_linux or build.platform_is_osx \
                or build.platform_is_bsd:
            # Check for liblilv-0
            if not conf.CheckLib('lilv-0'):
                raise Exception('Missing liblilv-0 (needs at least 0.5)')

            build.env.Append(CPPDEFINES='__LILV__')

    def sources(self, build):
        return ['effects/lv2/lv2backend.cpp',
                'effects/lv2/lv2effectprocessor.cpp',
                'effects/lv2/lv2manifest.cpp',
                'preferences/dialog/dlgpreflv2.cpp']

class Battery(Feature):
    def description(self):
        return "Battery meter support."

    def enabled(self, build):
        build.flags['battery'] = util.get_flags(build.env, 'battery', 1)
        if int(build.flags['battery']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('battery',
                 'Set to 1 to enable battery meter support.')

    def configure(self, build, conf):
        if not self.enabled(build):
            return

        build.env.Append(CPPDEFINES='__BATTERY__')

    def sources(self, build):
        if build.platform_is_windows:
            return ["util/battery/batterywindows.cpp"]
        elif build.platform_is_osx:
            return ["util/battery/batterymac.cpp"]
        elif build.platform_is_linux:
            return ["util/battery/batterylinux.cpp"]
        else:
            raise Exception('Battery support is not implemented for the target platform.')

    def depends(self, build):
        return [depends.IOKit, depends.UPower]

class QtKeychain(Feature):
    def description(self):
        return "Secure credentials storage support for Live Broadcasting profiles"

    def enabled(self, build):
        build.flags['qtkeychain'] = util.get_flags(build.env, 'qtkeychain', 0)
        if int(build.flags['qtkeychain']):
            return True
        return False

    def add_options(self, build, vars):
        vars.Add('qtkeychain', 'Set to 1 to enable secure credentials storage support for Live Broadcasting profiles', 0)

    def configure(self, build, conf):
        if not self.enabled(build):
            return
        build.env.Append(CPPDEFINES='__QTKEYCHAIN__')

    def sources(self, build):
        return []

    def depends(self, build):
        return [depends.QtKeychain]