prepare.py 19.1 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#!/usr/bin/env python

############################################################################
# prepare.py
# Copyright (C) 2015  Belledonne Communications, Grenoble France
#
############################################################################
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
21
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
22 23 24 25 26
#
############################################################################

import argparse
import os
27
import re
28
import subprocess
29 30 31
import sys
import urllib
import uuid
Ghislain MARY's avatar
Ghislain MARY committed
32
from logging import error, warning, info
33 34 35 36 37 38 39 40 41 42 43 44 45 46
from subprocess import Popen, PIPE
sys.dont_write_bytecode = True
sys.path.insert(0, 'submodules/cmake-builder')
try:
    import prepare
except Exception as e:
    error(
        "Could not find prepare module: {}, probably missing submodules/cmake-builder? Try running:\n"
        "git submodule sync && git submodule update --init --recursive".format(e))
    exit(1)


class Win10Target(prepare.Target):

47
    def __init__(self, arch, generator_platform = None):
48 49 50
        prepare.Target.__init__(self, 'win10-' + arch)
        current_path = os.path.dirname(os.path.realpath(__file__))
        current_path = current_path.replace('\\', '/')
51
        self.generator = 'Visual Studio 15 2017'
52
        self.platform_name = generator_platform
53 54
        self.config_file = 'configs/config-win10.cmake'
        self.output = 'OUTPUT/win10-' + arch
Ghislain MARY's avatar
Ghislain MARY committed
55
        self.external_source_path = os.path.join(current_path, 'submodules')
56 57 58 59
        external_builders_path = os.path.join(current_path, 'cmake_builder')
        self.additional_args = [
                "-DLINPHONE_BUILDER_EXTERNAL_BUILDERS_PATH=" + external_builders_path
                ]
60
        self.additional_args += ['-DCMAKE_CROSSCOMPILING=YES']
Ghislain MARY's avatar
Ghislain MARY committed
61 62 63 64
        self.additional_args += ['-DCMAKE_SYSTEM_NAME=WindowsStore']
        self.additional_args += ['-DCMAKE_SYSTEM_VERSION=10.0']
        self.additional_args += ['-DCMAKE_SYSTEM_PROCESSOR=' + arch]
        self.additional_args += ['-DCMAKE_VS_INCLUDE_INSTALL_TO_DEFAULT_BUILD=TRUE']
65 66 67 68 69 70 71 72 73 74 75


class Win10X86Target(Win10Target):

    def __init__(self):
        Win10Target.__init__(self, 'x86')


class Win10X64Target(Win10Target):

    def __init__(self):
76
        Win10Target.__init__(self, 'x64', 'x64')
77 78 79 80 81


class Win10ARMTarget(Win10Target):

    def __init__(self):
82
        Win10Target.__init__(self, 'ARM', 'ARM')
83 84


Ghislain MARY's avatar
Ghislain MARY committed
85
windows10_targets = {
86 87
    'x86': Win10X86Target(),
    'x64': Win10X64Target(),
Ghislain MARY's avatar
Ghislain MARY committed
88
    'ARM': Win10ARMTarget()
89
}
90
linphone_builder_targets = ['linphone', 'ms2', 'bellesip']
91 92


Ghislain MARY's avatar
Ghislain MARY committed
93
class ComponentListAction(argparse.Action):
94 95
    def __call__(self, parser, namespace, value, option_string=None):
        if value:
96
            if value not in linphone_builder_targets:
97
                message = ("Invalid target: {0!r} (choose from {1}".format(
Ghislain MARY's avatar
Ghislain MARY committed
98
                    value, ', '.join([repr(target) for target in linphone_builder_targets])))
99 100 101 102
                raise argparse.ArgumentError(self, message)
            setattr(namespace, self.dest, value)


Ghislain MARY's avatar
Ghislain MARY committed
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
class Windows10Preparator(prepare.Preparator):

    def __init__(self, targets=windows10_targets):
        prepare.Preparator.__init__(self, targets)
        self.veryclean = True
        self.argparser.add_argument('-ac', '--all-codecs', help="Enable all codecs, including the non-free ones", action='store_true')
        self.argparser.add_argument('--component', action=ComponentListAction, default='linphone', help="The component to build (default is 'linphone'). Can be one of: {0}.".format(', '.join([repr(target) for target in linphone_builder_targets])))


    def parse_args(self):
        prepare.Preparator.parse_args(self)

        if self.args.all_codecs:
            self.additional_args += ["-DENABLE_GPL_THIRD_PARTIES=YES"]
            self.additional_args += ["-DENABLE_NON_FREE_CODECS=YES"]
            self.additional_args += ["-DENABLE_AMRNB=YES"]
            self.additional_args += ["-DENABLE_AMRWB=YES"]
            self.additional_args += ["-DENABLE_G729=YES"]
            self.additional_args += ["-DENABLE_GSM=YES"]
            self.additional_args += ["-DENABLE_ILBC=YES"]
            self.additional_args += ["-DENABLE_ISAC=YES"]
            self.additional_args += ["-DENABLE_OPUS=YES"]
            self.additional_args += ["-DENABLE_SILK=YES"]
            self.additional_args += ["-DENABLE_SPEEX=YES"]
            self.additional_args += ["-DENABLE_FFMPEG=YES"]
            self.additional_args += ["-DENABLE_H263=YES"]
            self.additional_args += ["-DENABLE_H263P=YES"]
            self.additional_args += ["-DENABLE_MPEG4=YES"]
            self.additional_args += ["-DENABLE_OPENH264=YES"]
            self.additional_args += ["-DENABLE_VPX=YES"]
            self.additional_args += ["-DENABLE_X264=NO"]

        self.linphone_builder_target = self.args.component
        if self.linphone_builder_target == 'ms2':
137
            self.linphone_builder_target = 'ms2plugins'
Ghislain MARY's avatar
Ghislain MARY committed
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
        self.additional_args += ["-DLINPHONE_BUILDER_TARGET=" + self.linphone_builder_target]

    def clean(self):
        prepare.Preparator.clean(self)
        if os.path.isfile('SDK.sln'):
            os.remove('SDK.sln')
        if os.path.isfile('SDK.sdf'):
            os.remove('SDK.sdf')
        if os.path.isdir('WORK') and not os.listdir('WORK'):
            os.rmdir('WORK')
        if os.path.isdir('OUTPUT') and not os.listdir('OUTPUT'):
            os.rmdir('OUTPUT')

    def prepare(self):
        self.download_nuget()
        return prepare.Preparator.prepare(self)

    def nuget_download_reporthook(self, count, block_size, total_size):
        percent = int(count * block_size * 100 / total_size)
        sys.stdout.write("\r-- Downloading nuget: %2d%%" % percent)
        if percent == 100:
            sys.stdout.write('\n')
        sys.stdout.flush()

    def download_nuget(self):
        if not os.path.isdir('WORK'):
            os.makedirs("WORK")
        if not os.path.isfile('WORK/nuget.exe'):
            urllib.urlretrieve("https://dist.nuget.org/win-x86-commandline/latest/nuget.exe", "WORK/nuget.exe", reporthook = self.nuget_download_reporthook)

    def git_version(self, path):
        proc = subprocess.Popen(["git", "describe", "--always"], cwd=path, shell=False, stdout=subprocess.PIPE)
        out, err = proc.communicate()
        out = out.strip()
        pos = out.find('-g')
        if pos == -1:
            return out
175
        else:
Ghislain MARY's avatar
Ghislain MARY committed
176
            return out[:out.find('-g')].replace('-', '.')
177

Ghislain MARY's avatar
Ghislain MARY committed
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
    def generate_vs_solution(self):
        current_path = os.path.dirname(os.path.realpath(__file__))
        current_path = current_path.replace('\\', '/')
        guids = {}
        sln_projects = ""
        sln_confs = ""
        other_sdks = []
        build_type = 'Debug' if self.args.debug else 'Release'
        builder_target = []
        if self.linphone_builder_target == 'linphone':
            linphone_version = self.git_version('submodules/linphone')
            builder_target = [
                ('LinphoneTesterSDK', linphone_version),
                ('LinphoneSDK', linphone_version),
            ]
193
        elif self.linphone_builder_target == 'ms2plugins':
194
            ms2_version = self.git_version('submodules/mediastreamer2')
Ghislain MARY's avatar
Ghislain MARY committed
195 196 197
            builder_target = [
                ('MS2TesterSDK', ms2_version),
            ]
198
        elif self.linphone_builder_target == 'bellesip':
199
            bellesip_version = self.git_version('submodules/belle-sip')
Ghislain MARY's avatar
Ghislain MARY committed
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            builder_target = [
                ('BelleSipTesterSDK', bellesip_version),
            ]
        else:
            return

        vcxproj_platforms = {}
        for platform in self.args.target:
            if platform == 'x86':
                vcxproj_platforms[platform] = 'Win32'
            else:
                vcxproj_platforms[platform] = platform

        # Generate Visual Studio project to build the SDK for each platform
        for platform in self.args.target:
            guid = '{' + str(uuid.uuid4()).upper() + '}'
            guids[platform] = guid
217 218 219 220 221 222 223 224 225 226 227
            f = open("WORK/win10-{0}/cmake/ALL_BUILD.vcxproj".format(platform), 'r')
            all_build_content = f.read()
            f.close()
            m = re.search("ToolsVersion=\"(.*)\" xmlns", all_build_content)
            tools_version = m.group(1)
            m = re.search("<WindowsTargetPlatformVersion>(.*)</WindowsTargetPlatformVersion>", all_build_content)
            target_platform_version = m.group(1)
            m = re.search("<WindowsTargetPlatformMinVersion>(.*)</WindowsTargetPlatformMinVersion>", all_build_content)
            target_platform_min_version = m.group(1)
            m = re.search("<PlatformToolset>(.*)</PlatformToolset>", all_build_content)
            platform_toolset = m.group(1)
228
            arm = '\n    <WindowsSDKDesktopARMSupport>true</WindowsSDKDesktopARMSupport>' if platform == 'ARM' else ''
Ghislain MARY's avatar
Ghislain MARY committed
229
            vcxproj = """<?xml version="1.0" encoding="UTF-8"?>
230
<Project DefaultTargets="Build" ToolsVersion="{tools_version}" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
231
  <ItemGroup Label="ProjectConfigurations">
232 233
    <ProjectConfiguration Include="{build_type}|{vcxproj_platform}">
      <Configuration>{build_type}</Configuration>
234 235 236 237 238 239 240 241
      <Platform>{vcxproj_platform}</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGUID>{guid}</ProjectGUID>
    <ApplicationType>Windows Store</ApplicationType>
    <DefaultLanguage>en-US</DefaultLanguage>
    <ApplicationTypeRevision>10.0</ApplicationTypeRevision>
242
    <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>{arm}
243 244
    <WindowsTargetPlatformVersion>{target_platform_version}</WindowsTargetPlatformVersion>
    <WindowsTargetPlatformMinVersion>{target_platform_min_version}</WindowsTargetPlatformMinVersion>
245 246 247 248 249 250 251 252 253
    <Keyword>Win32Proj</Keyword>
    <Platform>{vcxproj_platform}</Platform>
    <ProjectName>SDK_{platform}</ProjectName>
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Label="Configuration">
    <ConfigurationType>Utility</ConfigurationType>
    <UseOfMfc>false</UseOfMfc>
    <CharacterSet>Unicode</CharacterSet>
254
    <PlatformToolset>{platform_toolset}</PlatformToolset>
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
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="PropertySheets">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
  </PropertyGroup>
  <ItemGroup>
    <CustomBuild Include="{current_path}/WORK/win10-{platform}/SDK_{platform}.rule">
      <Message>Building {platform} SDK</Message>
      <Command>setlocal
cd {current_path}/WORK/win10-{platform}/cmake
if %errorlevel% neq 0 goto :cmEnd
C:
if %errorlevel% neq 0 goto :cmEnd
cmake.exe --build . --config $(Configuration)
if %errorlevel% neq 0 goto :cmEnd
:cmEnd
endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd</Command>
      <AdditionalInputs>%(AdditionalInputs)</AdditionalInputs>
      <Outputs>{current_path}/WORK/win10-{platform}/Stamp/SDK-build</Outputs>
      <LinkObjects>false</LinkObjects>
    </CustomBuild>
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>
291
""".format(platform=platform, build_type=build_type, vcxproj_platform=vcxproj_platforms[platform], current_path=current_path, guid=guid, tools_version=tools_version, target_platform_version=target_platform_version, target_platform_min_version=target_platform_min_version, platform_toolset=platform_toolset, arm=arm)
Ghislain MARY's avatar
Ghislain MARY committed
292 293 294 295 296 297
            f = open("WORK/win10-{0}/SDK_{0}.vcxproj".format(platform), 'w')
            f.write(vcxproj)
            f.close()
            f = open("WORK/win10-{0}/SDK_{0}.rule".format(platform), 'w')
            f.close()
            sln_projects += \
Erwan Croze's avatar
Erwan Croze committed
298
"""Project("{{E8FB6309-B31E-4380-992C-BB1609B3EA00}}") = "SDK_{platform}", "WORK\win10-{platform}\SDK_{platform}.vcxproj", "{project_guid}"
299 300
EndProject
""".format(platform=platform, project_guid=guids[platform])
Ghislain MARY's avatar
Ghislain MARY committed
301
            sln_confs += """\t\t{project_guid}.{build_type}|Win32.ActiveCfg = {build_type}|{vcxproj_platform}
302 303
\t\t{project_guid}.{build_type}|Win32.Build.0 = {build_type}|{vcxproj_platform}
""".format(project_guid=guids[platform], platform=platform, build_type=build_type, vcxproj_platform=vcxproj_platforms[platform])
304

Ghislain MARY's avatar
Ghislain MARY committed
305 306 307 308
        # Generate Visual Studio projects to create a nuget packages
        for target, version in builder_target:
            guid = '{' + str(uuid.uuid4()).upper() + '}'
            vcxproj = """<?xml version="1.0" encoding="UTF-8"?>
309
<Project DefaultTargets="Build" ToolsVersion="{tools_version}" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
310
  <ItemGroup Label="ProjectConfigurations">
311 312
    <ProjectConfiguration Include="{build_type}|Win32">
      <Configuration>{build_type}</Configuration>
313 314 315 316 317 318 319 320 321
      <Platform>Win32</Platform>
    </ProjectConfiguration>
  </ItemGroup>
  <PropertyGroup Label="Globals">
    <ProjectGUID>{guid}</ProjectGUID>
    <ApplicationType>Windows Store</ApplicationType>
    <DefaultLanguage>en-US</DefaultLanguage>
    <ApplicationTypeRevision>10.0</ApplicationTypeRevision>
    <MinimumVisualStudioVersion>14.0</MinimumVisualStudioVersion>
322 323
    <WindowsTargetPlatformVersion>{target_platform_version}</WindowsTargetPlatformVersion>
    <WindowsTargetPlatformMinVersion>{target_platform_min_version}</WindowsTargetPlatformMinVersion>
324 325
    <Keyword>Win32Proj</Keyword>
    <Platform>Win32</Platform>
326
    <ProjectName>Nuget{target}</ProjectName>
327 328 329 330 331 332
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
  <PropertyGroup Label="Configuration">
    <ConfigurationType>Utility</ConfigurationType>
    <UseOfMfc>false</UseOfMfc>
    <CharacterSet>Unicode</CharacterSet>
333
    <PlatformToolset>{platform_toolset}</PlatformToolset>
334 335 336 337 338 339 340 341 342 343 344 345
  </PropertyGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
  <ImportGroup Label="ExtensionSettings">
  </ImportGroup>
  <ImportGroup Label="PropertySheets">
    <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IntDir>$(Platform)\$(Configuration)\$(ProjectName)\</IntDir>
  </PropertyGroup>
  <ItemGroup>
346 347
    <CustomBuild Include="{current_path}/WORK/NuGet{target}.rule">
      <Message>Generating NuGet package for {target}</Message>
348 349 350 351 352
      <Command>setlocal
cd {current_path}
if %errorlevel% neq 0 goto :cmEnd
C:
if %errorlevel% neq 0 goto :cmEnd
353
python.exe submodules/build/nuget.py -s OUTPUT -w WORK/NuGet{target} -cs CsWrapper -v {version} -t {target} {platforms}
354 355 356
if %errorlevel% neq 0 goto :cmEnd
cd {current_path}/OUTPUT
if %errorlevel% neq 0 goto :cmEnd
357
{current_path}/WORK/nuget.exe pack {current_path}/WORK/NuGet{target}/{target}.nuspec
358 359 360 361 362 363 364
:cmEnd
endlocal &amp; call :cmErrorLevel %errorlevel% &amp; goto :cmDone
:cmErrorLevel
exit /b %1
:cmDone
if %errorlevel% neq 0 goto :VCEnd</Command>
      <AdditionalInputs>%(AdditionalInputs)</AdditionalInputs>
365
      <Outputs>{current_path}/WORK/NuGet-build</Outputs>
366 367 368 369 370 371 372
      <LinkObjects>false</LinkObjects>
    </CustomBuild>
  </ItemGroup>
  <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
  <ImportGroup Label="ExtensionTargets">
  </ImportGroup>
</Project>
373
""".format(platforms=' '.join(self.args.target), target=target, build_type=build_type, version=version, current_path=current_path, guid=guid, tools_version=tools_version, target_platform_version=target_platform_version, target_platform_min_version=target_platform_min_version, platform_toolset=platform_toolset)
Ghislain MARY's avatar
Ghislain MARY committed
374 375 376 377 378 379 380 381
            f = open("WORK/NuGet{target}.vcxproj".format(target=target), 'w')
            f.write(vcxproj)
            f.close()
            f = open("WORK/NuGet{target}.rule".format(target=target), 'w')
            f.close()
            project_dependencies = ""
            for platform in self.args.target:
                project_dependencies += """\t\t{project_guid} = {project_guid}
382
""".format(project_guid=guids[platform])
383 384
            project_dependencies += """\t\t{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} = {FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}
"""
Ghislain MARY's avatar
Ghislain MARY committed
385 386
            for sdk in other_sdks:
                project_dependencies += """\t\t{project_guid} = {project_guid}
387
""".format(project_guid=guids[sdk])
Ghislain MARY's avatar
Ghislain MARY committed
388 389 390
            other_sdks += [target]
            guids[target] = guid
            sln_projects += \
Erwan Croze's avatar
Erwan Croze committed
391
"""Project("{{E8FB6309-B31E-4380-992C-BB1609B3EA00}}") = "Nuget{target}", "WORK\Nuget{target}.vcxproj", "{project_guid}"
392 393 394
\tProjectSection(ProjectDependencies) = postProject
{project_dependencies}\tEndProjectSection
EndProject
395
""".format(target=target, project_guid=guid, project_dependencies=project_dependencies)
Ghislain MARY's avatar
Ghislain MARY committed
396
            sln_confs += \
397 398 399
"""\t\t{project_guid}.{build_type}|Win32.ActiveCfg = {build_type}|Win32
\t\t{project_guid}.{build_type}|Win32.Build.0 = {build_type}|Win32
""".format(project_guid=guid, build_type=build_type)
400 401 402 403
            sln_confs += \
"""\t\t{project_guid}.{build_type}|Win32.ActiveCfg = {build_type}|Any CPU
\t\t{project_guid}.{build_type}|Win32.Build.0 = {build_type}|Any CPU
""".format(project_guid="{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}", build_type=build_type)
404

Ghislain MARY's avatar
Ghislain MARY committed
405 406
        # Generate Visual Studio solution to build the SDK
        sln = """Microsoft Visual Studio Solution File, Format Version 12.00
407
MinimumVisualStudioVersion = 10.0.40219.1
408
{sln_projects}Project("{{E8FB6309-B31E-4380-992C-BB1609B3EA00}}") = "CsWrapper", "CsWrapper\CsWrapper.csproj", "{{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}}"
Erwan Croze's avatar
Erwan Croze committed
409 410
\tProjectSection(ProjectDependencies) = postProject
{project_dependencies}\tEndProjectSection
411 412
EndProject
Global
413
\tGlobalSection(SolutionConfigurationPlatforms) = preSolution
414
\t\t{build_type}|Win32 = {build_type}|Win32
415 416 417 418 419 420 421
\tEndGlobalSection
\tGlobalSection(ProjectConfigurationPlatforms) = postSolution
{sln_confs}\tEndGlobalSection
\tGlobalSection(SolutionProperties) = preSolution
\t\tHideSolutionNode = FALSE
\tEndGlobalSection
EndGlobal
Erwan Croze's avatar
Erwan Croze committed
422
""".format(sln_projects=sln_projects, sln_confs=sln_confs, build_type=build_type, project_dependencies=project_dependencies)
Ghislain MARY's avatar
Ghislain MARY committed
423 424 425
        f = open('SDK.sln', 'w')
        f.write(sln)
        f.close()
426 427 428

        info("You can now build the SDK.sln Visual Studio Solution.")

Ghislain MARY's avatar
Ghislain MARY committed
429 430 431 432 433 434 435 436 437


def main():
    preparator = Windows10Preparator()
    preparator.parse_args()
    if preparator.check_environment() != 0:
        preparator.show_environment_errors()
        return 1
    return preparator.run()
438 439 440

if __name__ == "__main__":
    sys.exit(main())