How to build ffmpeg on windows

This page contains a list of resources which describe the necessary steps required for compiling FFmpeg from scratch or with the help of build scripts and/or package managers.

FFmpeg Compilation Guide

This page contains a list of resources which describe the necessary steps required for compiling FFmpeg from scratch or with the help of build scripts and/or package managers.

All platforms

Read the Generic compilation guide, regardless of your platform. It provides generic compilation and installation instructions, including the use of configure.

  • CompilationGuide/vcpkg – vcpkg also aims to be portable accross all platforms. For windows it uses MinGW/MSYS compilation toolchain.

Linux

  • Compiling FFmpeg on Ubuntu / Debian / Mint
  • Compiling FFmpeg on CentOS / RHEL / Fedora

Alternative ways to obtain/compile ffmpeg under Linux:

  • Docker image with pre-compiled ffmpeg and libraries
  • Linuxbrew

macOS

  • Compiling FFmpeg on macOS

Windows

  • CompilationGuide/MinGW – MinGW Compilation Guide for compiling FFmpeg with Windows/MinGW/MSYS.
  • CompilationGuide/CrossCompilingForWindows – Cross compiling for Windows is sometimes easier than using MSYS+MinGW.
  • CompilationGuide/WinRT – Compiling FFmpeg for Windows Apps (Windows 10 and Windows 8.1)
  • CompilationGuide/MSVC – Compiling FFmpeg using MSYS+MSVC, see also:
    • Instructions on the reference web page
    • Roxlu’s guide

Using external scripts or tools:

  • Media Autobuild Suite – Automatically build FFmpeg under Windows
  • Linuxbrew, which can be used with Windows Subsystem for Linux (WSL)
  • Chocolatey – a package manager for Windows with an FFmpeg package

Other Platforms

  • How to compile FFmpeg for Raspberry Pi (Raspbian)
  • Pre-compiled FFmpeg for Raspberry Pi (Raspbian) Docker image
  • How to compile FFmpeg for Android
  • How to cross-compile FFmpeg for MIPS
  • How to compile FFmpeg for Haiku

Performance Tips

There are numerous avenues to extract maximum performance out of FFmpeg when it is built from source. The following list describes some of them:

  • If using GCC/Clang, consider adding -march=native to --extra-cflags to make slightly better use of your hardware. Alternatively, for a more general solution, examine the --arch and --cpu options. Gains are variable, and usually quite small. However, this is usually even more safe than the above, and is thus listed here.
  • Depending on your use case, --enable-hardcoded-tables may be a useful option. It results in an increase of approximately 15% in the size of libavcodec, the main library impacted by this change. It enables savings in table generation time, done once at codec initialization, since by hardcoding the tables, they do not need to be computed at runtime. However, the savings are often negligible (~100k cycles is a typical number) especially when amortized over the entire encoding/decoding operation. By default, this is not enabled. Improvements are being made to the runtime initialization, and so over time, this option will have an impact on fewer and fewer codecs.
  • Other options may be found by examining ./configure --help.

Guides for developers

  • Setup Eclipse IDE for FFmpeg (Linux)

Compile and Use FFmpeg Libraries for Windows Runtime (Windows 10 or Windows 8.1 Apps)

  1. Compile and Use FFmpeg Libraries for Windows Runtime (Windows 10 or …
  2. Prerequisites and First Time Setup Instructions

    1. Prerequisites
    2. Verifying your FFmpeg Environment Setup
  3. Compiling for Windows 10

    1. Windows 10 x86
    2. Windows 10 x64
    3. Windows 10 ARM
  4. Compiling for Windows 8.1

    1. Windows Store 8.1 x86 (Windows 8.1 Win32 in Visual Studio)
    2. Windows Store 8.1 x64 (Windows 8.1 x64 in Visual Studio)
    3. Windows Store 8.1 ARM (Windows 8.1 ARM in Visual Studio)
    4. Windows Phone 8.1 x86 (Windows Phone 8.1 Win32 Emulator in Visual Studio)
    5. Windows Phone 8.1 ARM (Windows Phone 8.1 ARM Device in Visual Studio)
  5. Troubleshooting
  6. Windows Store Certification, File I/O, and Other Details
  7. Verifying Built FFmpeg Libraries and Sample Applications

FFmpeg libraries can be built and used for Windows Apps development targeting Windows 10, Windows 8.1, and Windows Phone 8.1. The guide below provides build instruction for all supported target configurations (platform & architecture). Each configuration requires distinct set of tools, environment variables, and configure options outlined in each section below. It concludes with some practical and potentially non-obvious information for consuming the FFmpeg DLLs from your app.


Prerequisites and First Time Setup Instructions

Prerequisites

  • For Windows 10: Microsoft Visual Studio 2015 (tested with Visual Studio 2015 RTM)
  • For Windows 8.1: Microsoft Visual Studio 2013 (use MSVC 2013 Update 3 RTM or newer)
  • MSYS2 (GNU Make environment)
  • YASM (x86 assembly code compiler)
  • gas-preprocessor.pl (ARM assembly pre-processor)

Windows 10 Setup

Download and install Microsoft Visual Studio 2015 on a Windows 10 machine.

Windows 8.1 Setup

Download and install Microsoft Visual Studio 2013 on a Windows 8.1 machine

MSYS2 Setup

Download the latest MSYS2 installer from http://msys2.github.io/ and follow the installation instruction closely from the installation webpage.
In order for the environment from the Windows side to be inherited on the MSYS2 side, uncomment the following line from msys2_shell.cmd if it is present:
replace rem set MSYS2_PATH_TYPE=inherit
with set MSYS2_PATH_TYPE=inherit this will allow the environment variables for Visual Studio to be transferred to the MSYS2 environment and back.

Once base MSYS2 is successfully installed, get the latest make package by invoking the following command in your MSYS2 shell

pacman -S make

Also get the latest gcc package

pacman -S gcc

Rename or remove link.exe in the MSYS2 usr bin folder (E.g. C:msys64usrbinlink.exe) to prevent conflict with MSVC link.exe

Install perl as it will be needed to run ‘gas-preprocessor.pl’

pacman -S perl

Install also diffutils for configure script

pacman -S diffutils

YASM Setup

Download YASM executable from http://yasm.tortall.net/Download.html. You have to download the «general use» binaries and NOT the ones for VS2010. Either Win32 or Win64 binaries support outputting object files for both architectures so that should not matter. The last tested version was yasm-1.3.0-win64.exe.

Rename the downloaded executable to yasm.exe and place it in your MSYS2 path. E.g.C:msys64usrbinyasm.exe.

gas-preprocessor Setup

Download gas-preprocessor.pl Perl script from https://github.com/FFmpeg/gas-preprocessor

Place the downloaded Perl script in your MSYS2 path. E.g. C:msys64usrbingas-preprocessor.pl

Verifying your FFmpeg Environment Setup

Launch Visual Studio ARM Cross Tools Command Prompt. E.g.

C:ProgramDataMicrosoftWindowsStart MenuProgramsVisual Studio 2015Visual Studio ToolsWindows Desktop Command PromptsVS2015 x86 ARM Cross Tools Command Prompt

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In the MSYS2 shell verify that all the tools below are setup properly by running the following commands

$ which cl
/c/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_ARM/cl

$ which link
/c/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_ARM/link

$ which armasm
/c/Program Files (x86)/Microsoft Visual Studio 14.0/VC/BIN/x86_ARM/armasm

$ which yasm
/usr/bin/yasm

$ which cpp
/usr/bin/cpp

$ which gas-preprocessor.pl
/usr/bin/gas-preprocessor.pl

Verify that the tools are in the path and point to the right location where MSYS2 and Visual Studio are installed


To keep the source tree clean and the platforms separated, we will have the intermediate files go to the Output<Platform><Architecture> folder under the FFmpeg source tree. We will also have the install files (the files necessary to link and use FFmpeg in your application) go to the Build<Platform><Architecture> folder under the FFmpeg source tree.


Compiling for Windows 10

Windows 10 x86

Launch VS2015 x86 Native Tools Command Prompt. E.g.

C:ProgramDataMicrosoftWindowsStart MenuProgramsVisual Studio 2015Visual Studio ToolsWindows Desktop Command PromptsVS2015 x86 Native Tools Command Prompt

Set the following environment variables in the launched command prompt above

SET LIB=%VSINSTALLDIR%VClibstore;%VSINSTALLDIR%VCatlmfclib;%UniversalCRTSdkDir%lib%UCRTVersion%ucrtx86;;%UniversalCRTSdkDir%lib%UCRTVersion%umx86;C:Program Files (x86)Windows KitsNETFXSDK4.6libumx86;;C:Program Files (x86)Windows KitsNETFXSDK4.6Libumx86
SET LIBPATH=%VSINSTALLDIR%VCatlmfclib;%VSINSTALLDIR%VClib;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%UniversalCRTSdkDir%Include%UCRTVersion%ucrt;%UniversalCRTSdkDir%Include%UCRTVersion%um;%UniversalCRTSdkDir%Include%UCRTVersion%shared;%UniversalCRTSdkDir%Include%UCRTVersion%winrt;C:Program Files (x86)Windows KitsNETFXSDK4.6Includeum;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows10/x86

cd Output/Windows10/x86

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=x86 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_APP -D_WIN32_WINNT=0x0A00" 
--extra-ldflags="-APPCONTAINER WindowsApp.lib" 
--prefix=../../../Build/Windows10/x86

make

make install

Generated libraries can be found in Build/Windows10/x86 folder specified in --prefix option above


Windows 10 x64

Launch VS2015 x86 x64 Cross Tools Command Prompt. E.g.

C:ProgramDataMicrosoftWindowsStart MenuProgramsVisual Studio 2015Visual Studio ToolsWindows Desktop Command PromptsVS2015 x86 x64 Cross Tools Command Prompt

Set the following environment variables in the launched command prompt above

SET LIB=%VSINSTALLDIR%VClibstoreamd64;%VSINSTALLDIR%VCatlmfclibamd64;%UniversalCRTSdkDir%lib%UCRTVersion%ucrtx64;;%UniversalCRTSdkDir%lib%UCRTVersion%umx64;C:Program Files (x86)Windows KitsNETFXSDK4.6libumx64;;C:Program Files (x86)Windows KitsNETFXSDK4.6Libumx64
SET LIBPATH=%VSINSTALLDIR%VCatlmfclibamd64;%VSINSTALLDIR%VClibamd64;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%UniversalCRTSdkDir%Include%UCRTVersion%ucrt;%UniversalCRTSdkDir%Include%UCRTVersion%um;%UniversalCRTSdkDir%Include%UCRTVersion%shared;%UniversalCRTSdkDir%Include%UCRTVersion%winrt;C:Program Files (x86)Windows KitsNETFXSDK4.6Includeum;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows10/x64

cd Output/Windows10/x64

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=x86_64 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_APP -D_WIN32_WINNT=0x0A00" 
--extra-ldflags="-APPCONTAINER WindowsApp.lib" 
--prefix=../../../Build/Windows10/x64

make

make install

Generated libraries can be found in Build/Windows10/x64 folder specified in --prefix option above

If you encounter an error linking because link.exe complains that MSPDB140.dll has the wrong version installed. Run the following command from an administrative command-prompt and rebuild:

copy "C:Program Files (x86)Microsoft Visual Studio 14.0VCbinmspdbsrv.exe" "C:Program Files (x86)Microsoft Visual Studio 14.0Common7IDE"

Windows 10 ARM

Launch VS2015 x86 ARM Cross Tools Command Prompt. E.g.

C:ProgramDataMicrosoftWindowsStart MenuProgramsVisual Studio 2015Visual Studio ToolsWindows Desktop Command PromptsVS2015 x86 ARM Cross Tools Command Prompt

Set the following environment variables in the launched command prompt above

SET LIB=%VSINSTALLDIR%VClibstoreARM;%VSINSTALLDIR%VCatlmfclibARM;%UniversalCRTSdkDir%lib%UCRTVersion%ucrtarm;;%UniversalCRTSdkDir%lib%UCRTVersion%umarm;C:Program Files (x86)Windows KitsNETFXSDK4.6libumarm;;C:Program Files (x86)Windows KitsNETFXSDK4.6Libumarm
SET LIBPATH=%VSINSTALLDIR%VCatlmfclibARM;%VSINSTALLDIR%VClibARM;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%UniversalCRTSdkDir%Include%UCRTVersion%ucrt;%UniversalCRTSdkDir%Include%UCRTVersion%um;%UniversalCRTSdkDir%Include%UCRTVersion%shared;%UniversalCRTSdkDir%Include%UCRTVersion%winrt;C:Program Files (x86)Windows KitsNETFXSDK4.6Includeum;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows10/ARM

cd Output/Windows10/ARM

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=arm 
--as=armasm 
--cpu=armv7 
--enable-thumb 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_APP -D_WIN32_WINNT=0x0A00 -D__ARM_PCS_VFP" 
--extra-ldflags="-APPCONTAINER WindowsApp.lib" 
--prefix=../../../Build/Windows10/ARM

make

make install

Generated libraries can be found in Build/Windows10/ARM folder specified in --prefix option above

If you encounter an error linking because link.exe complains that MSPDB140.dll has the wrong version installed. Run the following command from an administrative command-prompt and rebuild:

copy "C:Program Files (x86)Microsoft Visual Studio 14.0VCbinmspdbsrv.exe" "C:Program Files (x86)Microsoft Visual Studio 14.0Common7IDE"

Compiling for Windows 8.1

Windows Store 8.1 x86 (Windows 8.1 Win32 in Visual Studio)

Launch Developer Command Prompt for VS2013

Start Menu > Visual Studio 2013 (Start Menu Folder) > Visual Studio Tools > Developer Command Prompt for VS2013

Set the following environment variables in the launched command prompt above. These environment variables overwrite the default paths with correct target specific ones.

SET LIB=%VSINSTALLDIR%VClibstore;%VSINSTALLDIR%VCatlmfclib;%WindowsSdkDir%libwinv6.3umx86;;
SET LIBPATH=%WindowsSdkDir%ReferencesCommonConfigurationNeutral;;%VSINSTALLDIR%VCatlmfclib;%VSINSTALLDIR%VClib;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%WindowsSdkDir%Includeum;%WindowsSdkDir%Includeshared;%WindowsSdkDir%Includewinrt;;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows8.1/x86

cd Output/Windows8.1/x86

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-dxva2 
--arch=x86 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_PC_APP -D_WIN32_WINNT=0x0603" 
--extra-ldflags="-APPCONTAINER" 
--prefix=../../../Build/Windows8.1/x86

make

make install

Generated libraries can be found in Build/Windows8.1/x86 folder specified in --prefix option above


Windows Store 8.1 x64 (Windows 8.1 x64 in Visual Studio)

Launch VS2013 x64 Cross Tools Command Prompt

Start Menu > Visual Studio 2013 (Start Menu Folder) > Visual Studio Tools > VS2013 x64 Cross Tools Command Prompt

Set the following environment variables in the launched command prompt above. These environment variables overwrite the default paths with correct target specific ones.

SET LIB=%VSINSTALLDIR%VClibstoreamd64;%VSINSTALLDIR%VCatlmfclibamd64;%WindowsSdkDir%libwinv6.3umx64;;
SET LIBPATH=%WindowsSdkDir%ReferencesCommonConfigurationNeutral;;%VSINSTALLDIR%VCatlmfclibamd64;%VSINSTALLDIR%VClibamd64;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%WindowsSdkDir%Includeum;%WindowsSdkDir%Includeshared;%WindowsSdkDir%Includewinrt;;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows8.1/x64

cd Output/Windows8.1/x64

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-dxva2 
--arch=x86_64 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_PC_APP -D_WIN32_WINNT=0x0603" 
--extra-ldflags="-APPCONTAINER" 
--prefix=../../../Build/Windows8.1/x64

make

make install

Generated libraries can be found in Build/Windows8.1/x64 folder specified in --prefix option above


Windows Store 8.1 ARM (Windows 8.1 ARM in Visual Studio)

Launch VS2013 ARM Cross Tools Command Prompt

Start Menu > Visual Studio 2013 (Start Menu Folder) > Visual Studio Tools > VS2013 ARM Cross Tools Command Prompt

Set the following environment variables in the launched command prompt above. These environment variables overwrite the default paths with correct target specific ones.

SET LIB=%VSINSTALLDIR%VClibstoreARM;%VSINSTALLDIR%VCatlmfclibARM;%WindowsSdkDir%libwinv6.3umarm;;
SET LIBPATH=%WindowsSdkDir%ReferencesCommonConfigurationNeutral;;%VSINSTALLDIR%VCatlmfclibARM;%VSINSTALLDIR%VClibARM;
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%WindowsSdkDir%Includeum;%WindowsSdkDir%Includeshared;%WindowsSdkDir%Includewinrt;;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/Windows8.1/ARM

cd Output/Windows8.1/ARM

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=arm 
--as=armasm 
--cpu=armv7 
--enable-thumb 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_PC_APP -D_WIN32_WINNT=0x0603 -D__ARM_PCS_VFP" 
--extra-ldflags="-APPCONTAINER -MACHINE:ARM" 
--prefix=../../../Build/Windows8.1/ARM

make

make install

Generated libraries can be found in Build/Windows8.1/ARM folder specified in --prefix option above


Windows Phone 8.1 x86 (Windows Phone 8.1 Win32 Emulator in Visual Studio)

Launch Developer Command Prompt for VS2013

Start Menu > Visual Studio 2013 (Start Menu Folder) > Visual Studio Tools > Developer Command Prompt for VS2013

Set the following environment variables in the launched command prompt above. These environment variables overwrite the default paths with correct target specific ones.

SET LIB=%VSINSTALLDIR%VClibstore;%VSINSTALLDIR%VCatlmfclib;%WindowsSdkDir%....Windows Phone Kits8.1libx86;;
SET LIBPATH=%VSINSTALLDIR%VCatlmfclib;%VSINSTALLDIR%VClib
SET INCLUDE=%VSINSTALLDIR%VCINCLUDE;%VSINSTALLDIR%VCATLMFCINCLUDE;%WindowsSdkDir%....Windows Phone Kits8.1Include;%WindowsSdkDir%....Windows Phone Kits8.1Includeabi;%WindowsSdkDir%....Windows Phone Kits8.1Includemincore;%WindowsSdkDir%....Windows Phone Kits8.1Includeminwin;%WindowsSdkDir%....Windows Phone Kits8.1Includewrl;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/WindowsPhone8.1/x86

cd Output/WindowsPhone8.1/x86

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=x86 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_PHONE_APP -D_WIN32_WINNT=0x0603" 
--extra-ldflags="-APPCONTAINER -subsystem:console -opt:ref WindowsPhoneCore.lib RuntimeObject.lib PhoneAppModelHost.lib -NODEFAULTLIB:kernel32.lib -NODEFAULTLIB:ole32.lib" 
--prefix=../../../Build/WindowsPhone8.1/x86

make

make install

Generated libraries can be found in Build/WindowsPhone8.1/x86 folder specified in --prefix option above


Windows Phone 8.1 ARM (Windows Phone 8.1 ARM Device in Visual Studio)

Launch VS2013 ARM Cross Tools Command Prompt

Start Menu > Visual Studio 2013 (Start Menu Folder) > Visual Studio Tools > VS2013 ARM Cross Tools Command Prompt

Set the following environment variables in the launched command prompt above. These environment variables overwrite the default paths with correct target specific ones.

SET LIB=%VSINSTALLDIR%VClibstoreARM;%VSINSTALLDIR%VCatlmfclibARM;%WindowsSdkDir%....Windows Phone Kits8.1libarm;;
SET LIBPATH=%VSINSTALLDIR%VCatlmfclibARM;%VSINSTALLDIR%VClibARM
SET INCLUDE=%VSINSTALLDIR%VCinclude;%VSINSTALLDIR%VCatlmfcinclude;%WindowsSdkDir%....Windows Phone Kits8.1Include;%WindowsSdkDir%....Windows Phone Kits8.1Includeabi;%WindowsSdkDir%....Windows Phone Kits8.1Includemincore;%WindowsSdkDir%....Windows Phone Kits8.1Includeminwin;%WindowsSdkDir%....Windows Phone Kits8.1Includewrl;

Open MSYS2 Shell from the command prompt above (use the correct drive and location of your MSYS2 installation). Note that the command shell above will close and it may take a while for the MSYS2 shell to launch.

C:msys64msys2_shell.cmd

In your MSYS2 shell navigate to your cloned FFmpeg folder. E.g.

cd /c/ffmpeg

Invoke the following make commands

mkdir -p Output/WindowsPhone8.1/ARM

cd Output/WindowsPhone8.1/ARM

../../../configure 
--toolchain=msvc 
--disable-programs 
--disable-d3d11va 
--disable-dxva2 
--arch=arm 
--as=armasm 
--cpu=armv7 
--enable-thumb 
--enable-shared 
--enable-cross-compile 
--target-os=win32 
--extra-cflags="-MD -DWINAPI_FAMILY=WINAPI_FAMILY_PHONE_APP -D_WIN32_WINNT=0x0603 -D__ARM_PCS_VFP" 
--extra-ldflags="-APPCONTAINER -MACHINE:ARM -subsystem:console -opt:ref WindowsPhoneCore.lib RuntimeObject.lib PhoneAppModelHost.lib -NODEFAULTLIB:kernel32.lib -NODEFAULTLIB:ole32.lib" 
--prefix=../../../Build/WindowsPhone8.1/ARM

make

make install

Generated libraries can be found in Build/WindowsPhone8.1/ARM folder specified in --prefix option above


Troubleshooting

Building ARM libraries using Visual Studio armasm ARM assembler requires proper setup of gas-preprocessor.pl and Perl in your MSYS2 environment. Please follow the setup instruction closely.


Windows Store Certification, File I/O, and Other Details

FFmpeg is an excellent alternative to Windows Media Foundation, which supports a small fraction of the codecs that FFmpeg has. Fortunately,
FFmpeg does not use any prohibited Windows or CRT APIs, and apps linked to the DLLs built with this method pass the latest Windows App Certification Kit. However, there are important things to remember.

First, don’t forget to make sure your app package includes all the necessary FFmpeg DLLs in the root folder. In your Visual C++ project, you should include links to the FFmpeg DLLs in the root project folder, making sure to set «Build Action» to «Content» and «Copy to Output Directory» to «Copy Always». It is not enough just to link to the import libraries. You will fail certification if you require your users to install the FFmpeg DLLs separately.

You will also need to supply a custom file I/O context to any AVFormatContext rather than relying on avio_xxx functions, because the standard I/O functions utilize CRT I/O that is not supported in WinRT. (You won’t fail certification, but your app will be unable to access the file specified in the AVFormatContext.filename member, unless potentially it is located in the app’s local storage). The file I/O context needs to be initialized to point to your read, write, and seek functions, with the opaque member pointing to a struct containing an IRandomAccessStream^ that you obtain when opening a file using proper WinRT IO calls in the Windows::Storage namespace. (You need a struct to hold the IRandomAccessStream^, since you cannot cast a void* to a ref handle). Your read, write, and seek functions should cast the void* opaque argument to the struct* you define, and then use the IRandomAccessStream^ for all I/O.

Since FFmpeg I/O calls are synchronous, but the IRandomAccessStream members are all asynchronous, you will need to utilize create_task and wait() on all I/O calls in your IO context implementation functions. Note that this necessitates that any FFmpeg functions utilizing file I/O be executed on a WORKER thread, as WinRT will generate an exception if you use wait() in the UI thread. The best solution here is to create WinRT-friendly wrapper functions of the major FFmpeg functions you will utilize, by using the concurrency::create_async function, for example:

IAsyncOperation<int>^ av_read_frame_async(AVFormatContext* s, AVPacket* pkt)
{
	return create_async([s, pkt]()->int
	{
		return av_read_frame(s, pkt);
	});
}

Alternatively, if you don’t want to use Windows Runtime extensions, and don’t mind COM, you can use the Windows 8-API function CreateStreamOverRandomAccessStream, which gives you an IStream* COM interface from an IRandomAccessStream^, utilizes synchronous I/O, and can be passed as the void* opaque member of the IO context. The IStream I/O calls are easier to use with C++ since they support direct pointer buffer access (you don’t have to deal with IBuffer) and more closely correspond to the functions required in AVIOContext. However, you should still make sure to wrap any code that utilizes file I/O in a background thread, as excessive blocking of the UI does violate Windows Store guidelines and may cause your app to be terminated at runtime.


Verifying Built FFmpeg Libraries and Sample Applications

The generated FFmpeg libraries from the compilation above can be consumed by Windows Runtime Components or Apps. They can be tested against the interop component and sample media players in the following project:

https://github.com/Microsoft/FFmpegInterop

This is easier said than done, and has taken me over a month to figure out how to do without any issues, but I’ve spent enough time on it that I decided I’d document the process well enough to be completed virtually seamlessly by anyone following me.

Unfortunately, Cygwin’s default toolchain (i.e. the gcc-core package included with the Cygwin installer) is inherently broken for cross-compiling purposes, and there doesn’t seem to be any intent from the Cygwin maintainers to fix this, so currently, the only way to compile software for Windows with Cygwin is to set up a MinGW-w64 toolchain under it. Thankfully, this is as easy as installing a few packages. After this, we’ll be compiling the remaining packages, before using a combination of both to compile FFmpeg itself.

Using this Guide

Following this guide in its entirety will build a static FFmpeg installation with external libraries such as fdk-aac, libopus, x265 and the SOX resampler. I may consider adding instructions for compiling specific external libraries to the guide if I get enough requests to do so for a particular library.

The dependencies used by this guide — made up of the MinGW-w64 cross-compile toolchain itself, all packages installed by apt-cyg and all packages compiled from source — will consume up to 2.8GB of disk space, although the guide also includes commands to clean up everything but the FFmpeg installation once done. The installation itself, made up of the binaries and documentation, occupies just over 200MB of disk space.

This guide will create a folder in your Home directory called ffmpeg_sources, where it will download and compile all of the packages being built from source. FFmpeg will be installed to /usr/local, where the FHS standard recommends that software compiled by the user is installed to. This location also has the secondary advantage of being on the system PATH by default in Cygwin, and so doesn’t require the $PATH environment variable to be updated.

Install package manager dependencies

To begin with, download the latest version of the Cygwin installer to install the wget, tar, gawk and git packages. The good news is that these packages are dependencies for a tool that can prevent you from ever needing to use the Cygwin installer again.

Install the apt-cyg package manager

Next, install kou1okada’s fork of the apt-cyg package manager. If you don’t currently use a package manager for Cygwin, this step will not only make the rest of the guide a breeze, but will also make your Cygwin experience rival that of any Linux distribution.

Even if you already use a package manager for Cygwin, such as a different fork of the original apt-cyg, I highly recommend you replace it with this one, which is a much more fully-fledged piece of software compared to the original, as well as the only package manager for Cygwin that is currently in active development.

To install kou1okada’s apt-cyg:

mkdir -p /usr/local/src &&
cd /usr/local/src &&
git clone https://github.com/kou1okada/apt-cyg.git &&
ln -s "$(realpath apt-cyg/apt-cyg)" /usr/local/bin/

Install build tools and set up the MinGW-w64 cross-compiler

apt-cyg install 
autoconf 
automake 
binutils 
cmake 
doxygen 
git 
libtool 
make 
mercurial 
mingw64-x86_64-SDL2 
mingw64-x86_64-binutils 
mingw64-x86_64-fribidi 
mingw64-x86_64-gcc-core 
mingw64-x86_64-gcc-g++ 
mingw64-x86_64-headers 
mingw64-x86_64-libtheora 
mingw64-x86_64-libvpx 
mingw64-x86_64-runtime 
mingw64-x86_64-win-iconv 
mingw64-x86_64-windows-default-manifest 
mingw64-x86_64-zlib 
nasm 
pkg-config 
subversion 
texinfo 
yasm

Compile the dependencies

Each section below compiles an external library that will allow you to compile FFmpeg with support for that library enabled. Copy and paste the whole of each command into your shell.

If you decide you don’t require your build of FFmpeg to support a given library, skip its section and remove the corresponding --enable-package line when compiling FFmpeg in the final stage of this guide.

Create a directory at the root of your Cygwin installation with the following:

rm -rf /ffmpeg_sources &&
mkdir -p /ffmpeg_sources

This is the directory we’ll be downloading our source code to, and compiling it from.

libmp3lame

To compile the LAME audio codec for MP3:

cd /ffmpeg_sources && rm -rf lame-svn &&
svn checkout https://svn.code.sf.net/p/lame/svn/trunk/lame lame-svn &&
cd lame-svn &&
./configure --host=x86_64-w64-mingw32 --prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" 
--enable-static --disable-shared &&
make -j$(nproc) &&
make install 

libx264

To compile the x264 video codec:

cd /ffmpeg_sources && rm -rf x264 && 
git clone --depth 1 https://code.videolan.org/videolan/x264.git && 
cd x264 &&
./configure --cross-prefix=x86_64-w64-mingw32- --host=x86_64-w64-mingw32 
--prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" --enable-static &&
make -j$(nproc) &&
make install 

libx265

To compile the x265 video codec:

cd /ffmpeg_sources && rm -rf x265 && 
hg clone https://bitbucket.org/multicoreware/x265 &&
cd x265/build/linux &&
cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX="/usr/x86_64-w64-mingw32/sys-root/mingw" 
-DENABLE_SHARED=OFF -DCMAKE_EXE_LINKER_FLAGS="-static" ../../source 
-DCMAKE_TOOLCHAIN_FILE="/ffmpeg_sources/x265/build/msys/toolchain-x86_64-w64-mingw32.cmake" &&
make -j$(nproc) &&
make install

libogg/libvorbis

The Ogg format is a dependency for the Vorbis audio codec, so will need to be compiled before it:

cd /ffmpeg_sources && rm -rf ogg &&
git clone --depth 1 https://gitlab.xiph.org/xiph/ogg.git &&
cd ogg && ./autogen.sh &&
./configure --host=x86_64-w64-mingw32 --prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" 
--enable-static --disable-shared &&
make -j$(nproc) &&
make install

Then compile Vorbis as normal:

cd /ffmpeg_sources && rm -rf vorbis && 
git clone --depth 1 https://gitlab.xiph.org/xiph/vorbis.git &&
cd vorbis && ./autogen.sh &&
./configure --host=x86_64-w64-mingw32 --prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" 
--enable-static --disable-shared &&
make -j$(nproc) &&
make install

libaom

To compile the AV1 video encoder:

cd /ffmpeg_sources && rm -rf aom && 
git clone --depth 1 https://aomedia.googlesource.com/aom && 
mkdir -p /ffmpeg_sources/aom/build && cd /ffmpeg_sources/aom/build && 
cmake -G "Unix Makefiles" -DCMAKE_INSTALL_PREFIX="/usr/x86_64-w64-mingw32/sys-root/mingw" 
-DCMAKE_EXE_LINKER_FLAGS="-static" .. 
-DCMAKE_TOOLCHAIN_FILE="/ffmpeg_sources/aom/build/cmake/toolchains/x86_64-mingw-gcc.cmake" && 
make -j$(nproc) && 
make install

libopus

To compile the Opus audio encoder:

cd /ffmpeg_sources && rm -rf opus && 
git clone --depth 1 https://github.com/xiph/opus.git &&
cd opus && ./autogen.sh &&
./configure CFLAGS="-I/usr/local/llsp" --host=x86_64-w64-mingw32 --prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" 
--enable-static --disable-shared &&
make -j$(nproc) &&
make install

libfdk-aac

To compile the Fraunhofer FDK encoder for AAC:

cd /ffmpeg_sources && rm -rf fdk-aac && 
git clone --depth 1 https://github.com/mstorsjo/fdk-aac &&
cd fdk-aac && autoreconf -fiv &&
./configure --host=x86_64-w64-mingw32 --prefix="/usr/x86_64-w64-mingw32/sys-root/mingw" 
--enable-static --disable-shared &&
make -j$(nproc) &&
make install 

libsoxr

To compile the SOX resampler library, you’ll first need to create a CMAKE toolchain file for the MinGW-w64 toolchain as the project doesn’t include one by default.

Create a new file in the Cygwin root directory, and call it toolchain-x86_64-mingw32.cmake (make sure Windows is showing extensions, and that the extension is .cmake).

Copy and paste the following into the file:

SET(CMAKE_SYSTEM_NAME Windows)
SET(CMAKE_C_COMPILER /usr/bin/x86_64-w64-mingw32-gcc)
SET(CMAKE_CXX_COMPILER /usr/bin/x86_64-w64-mingw32-g++)
SET(CMAKE_RC_COMPILER /usr/bin/x86_64-w64-mingw32-windres)
SET(CMAKE_Fortran_COMPILER /usr/bin/x86_64-w64-mingw32-gfortran)
SET(CMAKE_AR:FILEPATH /usr/bin/x86_64-w64-mingw32-ar)
SET(CMAKE_RANLIB:FILEPATH /usr/bin/x86_64-w64-mingw32-ranlib)
SET(CMAKE_FIND_ROOT_PATH /usr/x86_64-w64-mingw32)
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
SET(QT_BINARY_DIR /usr/x86_64-w64-mingw32/bin /usr/bin)
SET(Boost_COMPILER -gcc47)

Now you can compile the SOX resampler as normal:

cd /ffmpeg_sources && rm -rf soxr &&  
git clone --depth 1 https://git.code.sf.net/p/soxr/code soxr &&
mkdir -p soxr/build && cd soxr/build &&
cmake -Wno-dev -DCMAKE_BUILD_TYPE=Release 
-DCMAKE_INSTALL_PREFIX="/usr/x86_64-w64-mingw32/sys-root/mingw" 
-DBUILD_SHARED_LIBS=OFF .. -DCMAKE_TOOLCHAIN_FILE="/toolchain-x86_64-mingw32.cmake" &&
make -j$(nproc) &&
make install

Compile the FFmpeg binary

The only thing that’s left to is compile FFmpeg itself, using the libraries downloaded or compiled above:

cd /ffmpeg_sources && rm -rf ffmpeg &&
wget -O ffmpeg-snapshot.tar.bz2 https://ffmpeg.org/releases/ffmpeg-snapshot.tar.bz2 &&
tar xvf ffmpeg-snapshot.tar.bz2 && rm -f ffmpeg-snapshot.tar.bz2 && cd ffmpeg &&
CFLAGS=-I/usr/x86_64-w64-mingw32/sys-root/mingw/include &&
LDFLAGS=-L/usr/x86_64-w64-mingw32/sys-root/mingw/lib &&
export PKG_CONFIG_PATH= &&
export PKG_CONFIG_LIBDIR=/usr/x86_64-w64-mingw32/sys-root/mingw/lib/pkgconfig &&
./configure 
--arch=x86_64 
--target-os=mingw32 
--cross-prefix=x86_64-w64-mingw32- 
--prefix=/usr/local 
--pkg-config=pkg-config 
--pkg-config-flags=--static 
--extra-cflags=-static 
--extra-ldflags=-static 
--extra-libs="-lm -lz -fopenmp" 
--enable-static 
--disable-shared 
--enable-nonfree 
--enable-gpl 
--enable-avisynth 
--enable-libaom 
--enable-libfdk-aac 
--enable-libfribidi 
--enable-libmp3lame 
--enable-libopus 
--enable-libsoxr 
--enable-libvorbis 
--enable-libvpx 
--enable-libx264 
--enable-libx265 &&
make -j$(nproc) &&
make install

Remember to remove --enable-*package* lines for each package in the list above that you didn’t download or compile a library for.

Compiling FFmpeg will take much longer than compilation of the external libraries, but once it’s done, you should have a fully working binary enabled with all of the libraries you compiled it with. To run it, simply run ffmpeg in the Cygwin terminal.

Clean up/uninstall

By this point in the guide, you will have taken up around 2.8 GB of disk space with downloading, installing and compiling. The majority of this is now redundant, and should be cleaned up. More than 2.6 GB of it can be safely purged, which brings the total footprint of our FFmpeg installation down to as little as 200MB.

Post-install clean up

Running the following will free up more than 2.3GB of disk space:

apt-cyg remove 
cmake 
doxygen 
git 
mercurial 
subversion 
texinfo 
yasm &&
rm -rf /ffmpeg_sources &&
rm -rf /usr/local/lib/{libav*,libpost*,libsw*} &&
rm -rf /usr/local/lib/pkgconfig/{libav*,libpost*,libsw*} &&
rm -rf /usr/local/include/{libav*,libpost*,libsw*} &&
rm -rf /toolchain-x86_64-mingw32.cmake

As well as removing the ffmpeg_sources directory and unneeded static libraries, this will also remove any packages installed earlier that are no longer needed, except for those that are commonly needed for building tools on Cygwin/Linux.

Remove the cross-compiler

If you no longer intend to compile any other programs using the MinGW-w64 cross-compiling toolchain built earlier in this guide, you can safely uninstall it, as well as all the remaining packages installed earlier:

apt-cyg remove 
autotools 
autoconf 
automake 
gcc-core 
gcc-g++ 
pkg-config 
libtool 
make 
nasm 
mingw64-x86_64-SDL2 
mingw64-x86_64-binutils 
mingw64-x86_64-fribidi 
mingw64-x86_64-gcc-core 
mingw64-x86_64-gcc-g++ 
mingw64-x86_64-headers 
mingw64-x86_64-libtheora 
mingw64-x86_64-libvpx 
mingw64-x86_64-runtime 
mingw64-x86_64-win-iconv 
mingw64-x86_64-windows-default-manifest 
mingw64-x86_64-zlib &&
rm -rf /usr/x86_64-w64-mingw32

This will free up an additional ~450 MB of space.

Uninstalling FFmpeg

If you ever need to reverse all of the steps in this guide and purge the FFmpeg binaries from your system, simply run the following:

apt-cyg remove 
autotools  
autoconf 
automake 
binutils 
cmake 
doxygen 
gcc-core 
gcc-g++ 
git 
libtool 
make 
mercurial 
mingw64-x86_64-SDL2 
mingw64-x86_64-binutils 
mingw64-x86_64-fribidi 
mingw64-x86_64-gcc-core 
mingw64-x86_64-gcc-g++ 
mingw64-x86_64-headers 
mingw64-x86_64-libtheora 
mingw64-x86_64-libvpx 
mingw64-x86_64-runtime 
mingw64-x86_64-win-iconv 
mingw64-x86_64-windows-default-manifest 
mingw64-x86_64-zlib 
nasm 
pkg-config 
subversion 
texinfo 
yasm &&
rm -rf /ffmpeg_sources &&
rm -rf /usr/local/bin{ffmpeg,ffprobe,ffplay} &&
rm -rf /usr/local/lib/{libav*,libpost*,libsw*} &&
rm -rf /usr/local/lib/pkgconfig/{libav*,libpost*,libsw*} &&
rm -rf /usr/local/include/{libav*,libpost*,libsw*} &&
rm -rf /usr/local/share/doc/ffmpeg &&
rm -rf /usr/local/share/ffmpeg &&
rm -rf /usr/local/share/man/man1/ff* &&
rm -rf /usr/local/share/man/man3/{libav*,libpost*,libsw*} &&
rm -rf /usr/x86_64-w64-mingw32/ &&
rm -rf /toolchain-x86_64-mingw32.cmake 

This will remove everything installed during the process of this guide, and revert your system to exactly how it was before starting it.

Instead of doing everything manually, you can use the media-autobuild_suite for Windows, which builds FFmpeg with almost all of its dependencies:

This Windows Batchscript setups a MinGW/GCC compiler environment for building ffmpeg and other media tools under Windows. After building the environment it retrieves and compiles all tools. All tools get static compiled, no external .dlls needed (with some optional exceptions)

The script gets continuously updated, and for most users, it will be the preferred way to get FFmpeg compiled under Windows.

The real answer is probably «no», but still, just to double check.
Has anyone ever been able to build ffmpeg x64 on Windows (VS2013 or VS2015)? I know it is not possible with publicly available sources without heavy modifications. However, if somebody did it and if he is willing to share a few tips…

Edit:
It is interesting how most of the required x64 tools for running the «configure» are distributed without dependencies and it is impossible to get them anywhere. Looks like a professional trolling.

Edit2:
There are thousands of errors like this:

fatal error C1083: Cannot open include file: 'features.h': No such file or directory

features.h is missing as many other header files. Is there a fix for that, or switching to Linux is the only option?

asked Dec 28, 2016 at 8:52

4

I used to compile ffmpeg on a linux machine with MinGW, but now I’m able to compile on a windows machine, in my case Windows 10.

NOTE:
For me it only worked for ffmpeg versions >= 3.0 and I tested using VS 2013 and 2015

Few steps but very important:

Download and install (except YASM):

  • Visual Studio 2013 or 2015
  • YASM
  • MSYS2

Steps:

  1. Install MSYS2 to a fixed folder (eg.: C:Devmsys64)
  2. Run msys2.exe
  3. Execute command «pacman -S make gcc diffutils» and press «Y» to install
  4. Close msys2
  5. Rename C:Devmsys64usrbinlink.exe to some other name (eg.: msys2_link.exe)
  6. Copy and rename «yasm—win64.exe» to «C:Devyasm.exe»
  7. Add «C:Dev» to environment variables PATH
  8. Run VS2013/2015 x86 (for x86) or x64 for (x64) Command Prompt
  9. Execute «C:Devmsys64msys2_shell.cmd -msys -use-full-path»
  10. On the msys2 window execute «which cl» and you should see the path of your VS
  11. Execute «which link» and you should also see the path of your VS
  12. Go to the ffmpeg source path (eg.: «cd /c/ffmpeg3.3»)
  13. Run ./configure and make

I use this configuration:

./configure 
    --toolchain=msvc 
    --arch=x86_64 
    --enable-yasm 
    --enable-asm
    --enable-shared 
    --enable-w32threads 
    --disable-programs 
    --disable-ffserver 
    --disable-doc 
    --disable-static 
    --prefix=/c/ffmpeg3.3/DLLS

NOTE2:
If you used the last line —prefix=/c/ffmpeg3.3/DLLS, as a final step, run make install and the binaries will be copied to that path

Hope it helped.

Best of luck

answered Jun 15, 2017 at 0:04

tweellt's user avatar

tweellttweellt

2,13319 silver badges28 bronze badges

2

Assuming with x64 you mean the standard 64-bit version, yes it is possible. See the fate page for all tested builds of FFmpeg, there’s various 32- and 64-bit versions of Visual Studio in that list, including VS2013 and VS2015 64-bit. Search for «Microsoft (R) C/C++ Optimizing Compiler Version 18.00.40629 for x64» (or «19.00.24215.1») or «VS2013″/»VS2015», all the way at the bottom. For exact build options, see here for 2013 or here for 2015. The important part is to open a Windows shell with the 64-bit commandline build tools in your $PATH and open a msys shell from there, and then run configure using the --arch=x86_64 --target-os=win64 --toolchain=msvc options. For more detail, see the MSVC compilation wiki page.

answered Dec 28, 2016 at 15:09

Ronald S. Bultje's user avatar

6

No, it cannot be done. MS compiler doesn’t support #include_next. Plus, many other problems… You need MinGW.

answered May 31, 2017 at 11:51

Malik Urac's user avatar

Malik UracMalik Urac

1321 silver badge8 bronze badges

There is a How-to on the FFmpeg Page itself.It didn’t work for me so far, but at least you should get rid of the C99 Errors and so on.

https://trac.ffmpeg.org/wiki/CompilationGuide/MSVC

Maybe you try installing this stuff (I had to download pkg-config seperatly with Msys2 for it to work) and follow these steps.

answered Apr 19, 2017 at 7:50

Earinor's user avatar

EarinorEarinor

251 silver badge6 bronze badges

3

17 Apr 2018

Как собрать библиотеку с поддержкой кодека h264 на большинстве платформ.

Зачем?

Библиотеку ffmpeg я использую для воспроизведения потока с камер. Понадобилось сделать SIP телефонию с поддержкой h264. Для этого нужно было пересобрать все имеющиеся библиотеки. Все файлы для сборки либо потерялись, либо были нерабочими. Пришлось пройти этот ад снова.

Исходники

FFmpeg

Я использовал версию 2.8, которая лежала у меня с незапамятных времен. Можно использовать версию старше.

  1. http:
  2. git clone -b release/2.8 https://github.com/FFmpeg/FFmpeg.git

x264

  1. ftp
  2. git clone http://git.videolan.org/git/x264.git

Cборка x264

Первым делом собираем libx264. Если не требуется переходим сразу к сборке FFmpeg

Windows

  1. Ставим VS Studio 2015 или выше. Минимальная версия VS2013 u2.
  2. Ставим MSYS2.
  3. Открываем консоль разработчика. Пуск/Visual Studio (Version)/Developer Command Promt. В ней будут доступны пути до компилятора и компоновщика.
  4. Из открытой консоли открываем консоль MSYS2.
    • C:msys64msys2_shell.cmd -mingw64 -full-path
    • mingw32 или mingw64 в зависимости от архитектуры
    • full-path — позволяет увидеть путь до компилятора (можно раскомментировать строчку set MSYS2_PATH_TYPE=inherit в msys2_shell.cmd)
  5. Переходим в папку с исходниками libx264.
  6. CC=cl ./configure --enable-static --prefix=${PWD}/installed
    make
    make install
    

iOS

  1. Переходим в папку с исходниками libx264. Это будет корень LIBX264_ROOT.
  2. Сборка будет происходить в папке [LIBX264_ROOT]/Projects/iOS/. Создаем папку mkdir -p Projects/iOS.
  3. Переходим в папку проекта.
  4. Создаем build_x264.sh. Копируем в него скрипт.
  5. Запускаем сборку библиотек: sh ./build_x264.sh.
  6. Файлы будут лежать в [LIBX264_ROOT]/Projects/iOS/Temp.
  7. Запускаем сборку FAT-либок. sh ./build_x264.sh lipo
  8. FAT-либка будут лежать в [LIBX264_ROOT]/lib/ios.

build_x264.sh


#!/bin/sh

CONFIGURE_FLAGS="--enable-static --enable-pic --disable-cli"

ARCHS="arm64 armv7 armv7s" #x86_64 i386

# folders
CWD=$(pwd)
TEMP_DIR=$CWD/Temp
mkdir -p $TEMP_DIR
# Go to ROOT
cd ../..
WORK_DIR=$(pwd)
# output dir
FAT=$WORK_DIR/lib/ios
mkdir -p $FAT

COMPILE="y"
LIPO="y"

#echo "temp dir=$TEMP_DIR"
#echo "work dir=$WORK_DIR"

# make this files executable
chmod +x $WORK_DIR/version.sh
chmod +x $WORK_DIR/tools/gas-preprocessor.pl
chmod +x $WORK_DIR/config.sub
chmod +x $WORK_DIR/config.guess

if [ "$*" ]
then
    if [ "$*" = "lipo" ]
    then
        # skip compile
        COMPILE=
    else
        ARCHS="$*"
        if [ $# -eq 1 ]
        then
            # skip lipo
            LIPO=
        fi
    fi
fi

if [ "$COMPILE" ]
then
    #CWD=$PWD
    for ARCH in $ARCHS
    do
        echo "building $ARCH..."
        mkdir -p "$TEMP_DIR/$ARCH"
        
        CFLAGS="-arch $ARCH"
        ASFLAGS=

        if [ "$ARCH" = "i386" -o "$ARCH" = "x86_64" ]
        then
            PLATFORM="iPhoneSimulator"
            CPU=
            if [ "$ARCH" = "x86_64" ]
            then
                CFLAGS="$CFLAGS -mios-simulator-version-min=7.0"
                HOST=
            else
                CFLAGS="$CFLAGS -mios-simulator-version-min=5.0"
            HOST="--host=i386-apple-darwin"
            fi
        else
            PLATFORM="iPhoneOS"
            if [ $ARCH = "arm64" ]
            then
                HOST="--host=aarch64-apple-darwin"
            XARCH="-arch aarch64"
            else
                HOST="--host=arm-apple-darwin"
            XARCH="-arch arm"
            fi
            CFLAGS="$CFLAGS -fembed-bitcode -mios-version-min=7.0"
            ASFLAGS="$CFLAGS"
        fi

        XCRUN_SDK=`echo $PLATFORM | tr '[:upper:]' '[:lower:]'`
        CC="xcrun -sdk $XCRUN_SDK clang"
        if [ $PLATFORM = "iPhoneOS" ]
        then
            export AS="$WORK_DIR/tools/gas-preprocessor.pl $XARCH -- $CC"
        else
            export -n AS
        fi
        CXXFLAGS="$CFLAGS"
        LDFLAGS="$CFLAGS"

        CC=$CC ./configure 
            $CONFIGURE_FLAGS 
            $HOST 
            --extra-cflags="$CFLAGS" 
            --extra-asflags="$ASFLAGS" 
            --extra-ldflags="$LDFLAGS" 
            --prefix="$TEMP_DIR/$ARCH" || exit 1

        make clean
        make -j3 install || exit 1

    done
fi

if [ "$LIPO" ]
then
    echo "building fat binaries..."
    
    set - $ARCHS
    THIN=$TEMP_DIR
    echo "$THIN"

    cd $THIN/$1/lib
    for LIB in *.a
    do
        cd $WORK_DIR
        echo lipo -create `find $THIN -name $LIB` -output $FAT/$LIB 1>&2
        lipo -create `find $THIN -name $LIB` -output $FAT/$LIB
    done

    cd $WORK_DIR
    #cp -rf $THIN/$1/include $WORK_DIR
fi

OSX

  1. Алгоритм сборки для OSX совпадает с iOS. Немного отличается скрипт и рабочая папка [LIBX264_ROOT]/Projects/OSX/
  2. На моей машине для i386 сразу создавалась FAT-либка. Я просто копировал ее в [LIBX264_ROOT]/lib/osx/

build_x264.sh


#!/bin/sh

CONFIGURE_FLAGS="--enable-static --enable-pic --disable-cli --disable-asm"

ARCHS="x86_64 i386" #

# directiries
CWD=$(pwd)
TEMP_DIR=$CWD/Temp
mkdir -p $TEMP_DIR
cd ../..
WORK_DIR=$(pwd)
FAT=$WORK_DIR/lib/osx
mkdir -p $FAT

COMPILE="y"
LIPO="y"

echo "temp dir=$TEMP_DIR"
echo "work dir=$WORK_DIR"

chmod +x $WORK_DIR/version.sh
chmod +x $WORK_DIR/tools/gas-preprocessor.pl
chmod +x $WORK_DIR/config.sub
chmod +x $WORK_DIR/config.guess

if [ "$*" ]
then
    if [ "$*" = "lipo" ]
    then
        # skip compile
        COMPILE=
    else
        ARCHS="$*"
        if [ $# -eq 1 ]
        then
            # skip lipo
            LIPO=
        fi
    fi
fi

if [ "$COMPILE" ]
then
    #CWD=$PWD
    for ARCH in $ARCHS
    do
        echo "building $ARCH..."
        mkdir -p "$TEMP_DIR/$ARCH"
        
        CFLAGS="-arch $ARCH"
        ASFLAGS=
        
        PLATFORM="macosx"
        XCRUN_SDK=`echo $PLATFORM | tr '[:upper:]' '[:lower:]'`
        CC="xcrun -sdk $XCRUN_SDK clang"
        
        CXXFLAGS="$CFLAGS"
        LDFLAGS="$CFLAGS"

        CC=$CC ./configure 
            $CONFIGURE_FLAGS 
            $HOST 
            --extra-cflags="$CFLAGS" 
            --extra-asflags="$ASFLAGS" 
            --extra-ldflags="$LDFLAGS" 
            --prefix="$TEMP_DIR/$ARCH" || exit 1

        make clean
        make -j3 install || exit 1

    done
fi

# TODO i386 makes fat lib. need only cp Temp/i386/lib/*.a $WORK_DIR/lib/osx
if [ "$LIPO" ]
then
    echo "building fat binaries..."
    cp Temp/i386/lib/*.a $WORK_DIR/lib/osx

    #set - $ARCHS
    #THIN=$TEMP_DIR
    #echo "$THIN"

    #cd $THIN/$1/lib
    #for LIB in *.a
    #do
    #    cd $WORK_DIR
    #    echo lipo -create `find $THIN -name $LIB` -output $FAT/$LIB 1>&2
    #    lipo -create `find $THIN -name $LIB` -output $FAT/$LIB
    #done

    #cd $WORK_DIR
    #cp -rf $THIN/$1/include $WORK_DIR
fi

Android

  1. Ставим Cygwin (Mingw,MSYS2).
  2. Ставим Android NDK. Раньше качался отдельно, сейчас только через SDK Manager в Android Studio.
  3. Открываем консоль Cygwin.
  4. Переходим в папку с исходниками cd /cygdrive/{disk letter}/{path to x264}/.
  5. Создаем папку mkdir -p Projects/Android.
  6. cd Projects/Android
  7. Создаем build_x264.sh. Копируем в него скрипт.
  8. Правим переменные NDK, SYSROOT, TOOLCHAIN, ARCH.
  9. Запускаем сборку библиотек: sh ./build_x264.sh.

build_x264.sh


#!/bin/sh

NDK=C:/Users/UserName/AppData/Local/Android/sdk/ndk-bundle
SYSROOT=$NDK/platforms/android-16/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64

ARCH=armeabi-v7a
WORK_DIR=$(pwd)
TEMP_DIR=$WORK_DIR/temp
ROOT_DIR=$WORK_DIR/../..
PREFIX=$TEMP_DIR/$ARCH

delete()
{
   echo "================== Deleting libs"
   rm ./lib/android/*.a
}

copy_libs()
{
   echo "================== Copy libs"
   OUT_DIR=$ROOT_DIR/lib/android/$ARCH
   mkdir -p $OUT_DIR
   cp $PREFIX/lib/*.a $OUT_DIR
}

build_armv7()
{
   ./configure 
    --prefix=$PREFIX 
    --enable-static 
    --enable-pic 
    --host=arm-linux 
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- 
    --sysroot=$SYSROOT
	
    make clean
	make
	make install
}

cd ../..

echo $(pwd)

build_armv7
copy_libs 

Cборка FFmpeg

Windows

  1. Ставим VS Studio 2015 или выше. Минимальная версия VS2013 u2.
  2. Ставим MSYS2.
  3. Открываем консоль разработчика. Пуск/Visual Studio (Version)/Developer Command Promt. В ней будут доступны пути до компилятора и компоновщика.
  4. Из открытой консоли открываем консоль MSYS2.
    • C:msys64msys2_shell.cmd -mingw64 -full-path
    • mingw32 или mingw64 в зависимости от архитектуры
    • full-path — позволяет увидеть путь до компилятора (можно раскомментировать строчку set MSYS2_PATH_TYPE=inherit в msys2_shell.cmd)
  5. Переходим в папку с исходниками ffmpeg.
  6. ./configure --toolchain=msvc --disable-shared --disable-doc --disable-ffmpeg --disable-ffplay --disable-ffprobe --disable-ffserver 
     --disable-avdevice --disable-symver --enable-libx264 --enable-gpl --prefix=${PWD}/installed
     --extra-cflags="-IC:\x264\installed\include"
     --extra-ldflags="-LC:\x264\installed\lib"
    
    • –disable-shared — статические библиотеки, –disable-static — динамические.
    • –disable-asm — если будет ругаться на ассемблерные вставки. Я собирал без него на vs2015. Если использовать vs2010, то придется потанцевать с yasm(nasm), c99conv, c99wrap.
    • –arch=x86_64 — если требуется собрать x64 архитектуру. Должен быть MSYS64 и libx264 с x64 архитектурой.
    • –prefix — укажет папку куда выполнится make install.
    • –extra-ldflags — не работает на win7. ругается на линковку libx264.a. Нужно перенести libx264 в корень ffmpeg, либо в temp папку, которую создает configure в корне при выполнении.
    • если не использовать –prefix собраные либы будут лежать в подпапках рядом с исходниками.

iOS

  1. Переходим в папку с исходниками ffmpeg. Это будет корень FFMPEG_ROOT.
  2. Сборка будет происходить в папке [FFMPEG_ROOT]/Projects/iOS/. Создаем папку mkdir -p Projects/iOS.
  3. Переходим в папку проекта.
  4. Создаем build_ffmpeg.sh. Копируем в него скрипт.
  5. Правим пути до libx264 (если требуется).
  6. Запускаем сборку библиотек: sh ./build_ffmpeg.sh.
  7. Файлы будут лежать в [FFMPEG_ROOT]/Projects/iOS/Temp.
  8. Запускаем сборку FAT-либок. sh ./build_ffmpeg.sh lipo
  9. FAT-либка будут лежать в [build_ffmpeg]/lib/ios.

build_ffmpeg.sh


#!/bin/sh

# ffmpeg_build.sh

FFMPEG_SOURCE=ffmpeg-2.8
ARCHS="arm64 armv7s armv7" #x86_64 i386

CONFIGURE_FLAGS="--enable-cross-compile
                 --disable-debug
                 --disable-programs 
                 --disable-doc
                 --disable-bzlib 
                 --enable-pic"

# folders
CWD=$(pwd)
TEMP_DIR=$CWD/Temp
mkdir -p $TEMP_DIR
cd ../..
WORK_DIR=$(pwd)
FAT=$WORK_DIR/lib/ios
mkdir -p $FAT

chmod +x ./configure
chmod +x ./version.sh

# absolute path to x264 library
X264="$WORK_DIR/../x264/Project/iOS/Temp"

echo "temp dir=$TEMP_DIR"
echo "work dir=$WORK_DIR"
echo "x264 dir=$X264"

if [ "$X264" ]
then
    CONFIGURE_FLAGS="$CONFIGURE_FLAGS --enable-gpl --enable-libx264"
fi

#echo "$CONFIGURE_FLAGS"

COMPILE="y"
LIPO="y"
DEPLOYMENT_TARGET="7.0"

if [ "$*" ]
then
    if [ "$*" = "lipo" ]
    then
        # skip compile
        COMPILE=
    else
        ARCHS="$*"
        if [ $# -eq 1 ]
        then
            # skip lipo
            LIPO=
        fi
    fi
fi

if [ "$COMPILE" ]
then
    # install dependences
    if [ ! `which yasm` ]
    then
        echo 'Yasm not found'
        if [ ! `which brew` ]
        then
            echo 'Homebrew not found. Trying to install...'
                        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 
                || exit 1
        fi
        echo 'Trying to install Yasm...'
        brew install yasm || exit 1
    fi
    if [ ! `which gas-preprocessor.pl` ]
    then
        echo 'gas-preprocessor.pl not found. Trying to install...'
        (curl -L https://github.com/libav/gas-preprocessor/raw/master/gas-preprocessor.pl 
            -o /usr/local/bin/gas-preprocessor.pl 
            && chmod +x /usr/local/bin/gas-preprocessor.pl) 
            || exit 1
    fi

    # arch loop
    for ARCH in $ARCHS
    do
        echo "building $ARCH..."
        mkdir -p "$TEMP_DIR/$ARCH"
        #cd "$TEMP_DIR/$ARCH"

        CFLAGS="-arch $ARCH"
        if [ "$ARCH" = "i386" -o "$ARCH" = "x86_64" ]
        then
            PLATFORM="iPhoneSimulator"
            CFLAGS="$CFLAGS -mios-simulator-version-min=$DEPLOYMENT_TARGET"
        else
            PLATFORM="iPhoneOS"
            CFLAGS="$CFLAGS -mios-version-min=$DEPLOYMENT_TARGET -fembed-bitcode"
            if [ "$ARCH" = "arm64" ]
            then
                EXPORT="GASPP_FIX_XCODE5=1"
            fi
        fi

        XCRUN_SDK=`echo $PLATFORM | tr '[:upper:]' '[:lower:]'`
        CC="xcrun -sdk $XCRUN_SDK clang"

        # force "configure" to use "gas-preprocessor.pl" (FFmpeg 3.3)
        if [ "$ARCH" = "arm64" ]
        then
            AS="gas-preprocessor.pl -arch aarch64 -- $CC"
        else
            AS="$CC"
        fi

        CXXFLAGS="$CFLAGS"
        LDFLAGS="$CFLAGS"
        if [ "$X264" ]
        then
            CFLAGS="$CFLAGS -I$X264/$ARCH/include"
            LDFLAGS="$LDFLAGS -L$X264/$ARCH/lib"
        fi
        if [ "$FDK_AAC" ]
        then
            CFLAGS="$CFLAGS -I$FDK_AAC/include"
            LDFLAGS="$LDFLAGS -L$FDK_AAC/lib"
        fi

        # build
        ./configure 
            --target-os=darwin 
            --arch=$ARCH 
            --cc="$CC" 
            --as="$AS" 
            $CONFIGURE_FLAGS 
            --extra-cflags="$CFLAGS" 
            --extra-ldflags="$LDFLAGS" 
            --prefix="$TEMP_DIR/$ARCH" 
        || exit 1

        make clean
        make -j3 install || exit 1
        
    done
fi

if [ "$LIPO" ]
then
    echo "building fat binaries..."
    #mkdir -p $FAT
    set - $ARCHS
    #CWD=`pwd`
    #cd $THIN/$1/lib
    #echo "==== $1"
    THIN=$TEMP_DIR

    echo "$THIN"
    cd $THIN/$1/lib/
    for LIB in *.a
    do
        cd $WORK_DIR
        
        echo lipo -create `find $THIN -name $LIB` -output $FAT/$LIB 1>&2
        lipo -create `find $THIN -name $LIB` -output $FAT/$LIB || exit 1
    done

    cd $WORK_DIR
    cp -rf $THIN/$1/include $WORK_DIR
fi

OSX

  1. Переходим в папку с исходниками ffmpeg. Это будет корень FFMPEG_ROOT.
  2. Сборка будет происходить в папке [FFMPEG_ROOT]/Projects/OSX/. Создаем папку mkdir -p Projects/OSX.
  3. Переходим в папку проекта.
  4. Создаем build_ffmpeg.sh. Копируем в него скрипт.
  5. Правим пути до libx264 (если требуется).
  6. Запускаем сборку библиотек: sh ./build_ffmpeg.sh.
  7. Файлы будут лежать в [FFMPEG_ROOT]/Projects/OSX/Temp.
  8. Запускаем сборку FAT-либок. sh ./build_ffmpeg.sh lipo
  9. FAT-либка будут лежать в [build_ffmpeg]/lib/osx.

build_ffmpeg.sh


#!/bin/sh

FFMPEG_SOURCE=ffmpeg-2.8
ARCHS="x86_64 i386" #

CONFIGURE_FLAGS="--enable-cross-compile
                 --disable-debug
                 --disable-programs 
                 --disable-doc
                 --disable-bzlib 
                 --disable-asm 
                 --disable-vda 
                 --enable-pic"

# folders
CWD=$(pwd)
TEMP_DIR=$CWD/Temp
mkdir -p $TEMP_DIR
cd ../..
WORK_DIR=$(pwd)
FAT=$WORK_DIR/lib/osx
mkdir -p $FAT

chmod +x ./configure
chmod +x ./version.sh

# absolute path to x264 library
X264="$WORK_DIR/../x264/Project/OSX/Temp"

echo "temp dir=$TEMP_DIR"
echo "work dir=$WORK_DIR"
echo "x264 dir=$X264"

if [ "$X264" ]
then
    CONFIGURE_FLAGS="$CONFIGURE_FLAGS --enable-gpl --enable-libx264"
fi

#echo "$CONFIGURE_FLAGS"

COMPILE="y"
LIPO="y"
DEPLOYMENT_TARGET="7.0"

if [ "$*" ]
then
    if [ "$*" = "lipo" ]
    then
        # skip compile
        COMPILE=
    else
        ARCHS="$*"
        if [ $# -eq 1 ]
        then
            # skip lipo
            LIPO=
        fi
    fi
fi

if [ "$COMPILE" ]
then
    # install dependences
    if [ ! `which yasm` ]
    then
        echo 'Yasm not found'
        if [ ! `which brew` ]
        then
            echo 'Homebrew not found. Trying to install...'
                        ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)" 
                || exit 1
        fi
        echo 'Trying to install Yasm...'
        brew install yasm || exit 1
    fi
    if [ ! `which gas-preprocessor.pl` ]
    then
        echo 'gas-preprocessor.pl not found. Trying to install...'
        (curl -L https://github.com/libav/gas-preprocessor/raw/master/gas-preprocessor.pl 
            -o /usr/local/bin/gas-preprocessor.pl 
            && chmod +x /usr/local/bin/gas-preprocessor.pl) 
            || exit 1
    fi

    # arch loop
    for ARCH in $ARCHS
    do
        echo "building $ARCH..."
        mkdir -p "$TEMP_DIR/$ARCH"

        CFLAGS="-arch $ARCH"
        PLATFORM="macosx"
        XCRUN_SDK=`echo $PLATFORM | tr '[:upper:]' '[:lower:]'`
        CC="xcrun -sdk $XCRUN_SDK clang"

        CXXFLAGS="$CFLAGS"
        LDFLAGS="$CFLAGS"
        if [ "$X264" ]
        then
            CFLAGS="$CFLAGS -I$X264/$ARCH/include"
            LDFLAGS="$LDFLAGS -L$X264/$ARCH/lib"
        fi
        if [ "$FDK_AAC" ]
        then
            CFLAGS="$CFLAGS -I$FDK_AAC/include"
            LDFLAGS="$LDFLAGS -L$FDK_AAC/lib"
        fi

        # 
        ./configure 
            --target-os=darwin 
            --arch=$ARCH 
            --cc="$CC" 
            --as="$AS" 
            $CONFIGURE_FLAGS 
            --extra-cflags="$CFLAGS" 
            --extra-ldflags="$LDFLAGS" 
            --prefix="$TEMP_DIR/$ARCH" 
        || exit 1

        make clean
        make -j3 install || exit 1
        
    done
fi

if [ "$LIPO" ]
then
    echo "building fat binaries..."
    #mkdir -p $FAT
    set - $ARCHS
    THIN=$TEMP_DIR

    echo "$THIN"
    cd $THIN/$1/lib/
    for LIB in *.a
    do
        cd $WORK_DIR
        
        echo lipo -create `find $THIN -name $LIB` -output $FAT/$LIB 1>&2
        lipo -create `find $THIN -name $LIB` -output $FAT/$LIB || exit 1
    done

    cd $WORK_DIR
    cp -rf $THIN/$1/include $WORK_DIR
fi

Android

  1. Ставим Cygwin (Mingw,MSYS2).
  2. Ставим Android NDK. Раньше качался отдельно, сейчас только через SDK Manager в Android Studio.
  3. Открываем консоль Cygwin.
  4. Переходим в папку с исходниками cd /cygdrive/{disk letter}/{path to ffmpeg}/.
  5. Создаем папку mkdir -p Projects/Android.
  6. cd Projects/Android
  7. Создаем build_ffmpeg.sh. Копируем в него скрипт.
  8. Правим переменные NDK, SYSROOT, TOOLCHAIN, ARCH.
  9. Запускаем сборку библиотек: sh ./build_ffmpeg.sh.

build_ffmpeg.sh


#!/bin/sh

FFMPEG_SOURCE=ffmpeg-2.8

# start cygwin
# cd /cygdrive/{disk letter}/{path to iridium}/libs/$FFMPEG_SOURCE/Projects/Android
# ./{this file}

NDK=C:/Users/UserName/AppData/Local/Android/sdk/ndk-bundle
SYSROOT=$NDK/platforms/android-16/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.9/prebuilt/windows-x86_64

ARCH=armv7-a
FARCH=armeabi-v7a
WORK_DIR=$(pwd)
#TEMP_DIR=$WORK_DIR/temp
TEMP_DIR=D:/Work/iridium/trunk/Android/libs/ffmpeg-2.8/Projects/Android/temp
ROOT_DIR=$WORK_DIR/../..
PREFIX=$TEMP_DIR/$FARCH

export TMPDIR=D:/tmp

X264_DIR=D:/Work/iridium/trunk/Android/libs/x264/Projects/Android/temp/armeabi-v7a
X264_CFLAGS="-I$X264_DIR/include"
X264_LDFLAGS="-L$X264_DIR/lib"

delete()
{
   echo "================== Deleting libs"
   rm ./lib/android/*.a
}

copy_libs()
{
   echo "================== Copy libs"
   #cp lib/osx/x86_32/usr/local/lib/*.a lib/android
   OUT_DIR=$ROOT_DIR/lib/android/$FARCH
   mkdir -p $OUT_DIR
   cp $PREFIX/lib/*.a $OUT_DIR
}

build_armv7()
{
   ./configure 
    --prefix=$PREFIX 
    --enable-static 
    --disable-shared 
    --disable-doc 
    --disable-programs 
    --disable-avdevice 
    --disable-bzlib 
    --disable-doc 
    --disable-symver 
    --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- 
    --target-os=linux 
    --arch=arm 
    --cpu=cortex-a8 
    --enable-cross-compile 
    --sysroot=$SYSROOT 
    --enable-gpl 
    --enable-libx264 
    --extra-cflags="-Os -fpic -march=$ARCH -mfloat-abi=softfp -mfpu=vfpv3 -marm $X264_CFLAGS" 
    --extra-ldflags="$X264_LDFLAGS" 
    $ADDITIONAL_CONFIGURE_FLAG || exit 1
	
    make clean
	make
	make install
}

cd ../..

build_armv7

Ссылки

  1. FFmpeg
  2. VS build FFmpeg
  3. build ios script


Оставить комментарий через Telegram

I’m a big fan of the FFmpeg builds by Kyle Schwarz
though recently the website was down and I had to compile FFmpeg
manually. Although compiling FFmpg on Windows is simple, once
you’ve figured out the details, it will still take you some time
to get it right.

Therefore I’m providing these instructions that you can follow
step-by-step and will build a shared library for FFmpeg with X264.
Note that at the time of writing you can’t link
statically with X264, see the X264_API_IMPORTS define in
FFmpegs source. I’ve tried to keep things as short as possible.
Hit me up on Twitter when you have
any questions. Thanks Matthias C. M. Troffaes for
providing fixes that allow us to compile X264 with MSVC with MSYS2.

You can download the shell script containing all the steps
from this gist

1. Install MSYS2

  • Download MSYS2, msys2-x86_64-{date}.exe
  • Install into c:/msys64
  • Edit c:/msys64/msys2_shell.cmd and remove rem from the line with rem MSYS2_PATH_TYPE=inherit
  • Open a x64 Native Tools Command Prompt for VS 2019
  • Run c:/msys64/msys2_shell.cmd
  • Use the MSYS2 shell for the next steps and enter:
pacman -Syu
pacman -S make
pacman -S diffutils
pacman -S yasm
pacman -S nasm
 
mv /usr/bin/link.exe /usr/bin/link.exe.bak

2. Get the sources for x264 and ffmpeg

mkdir tmp
cd tmp
mkdir sources
mkdir build
cd sources
 
git clone --depth 1 https://code.videolan.org/videolan/x264.git
git clone --depth 1 git://source.ffmpeg.org/ffmpeg.git

3. Fix the build scripts for x264

cd tmp/sources/x264
curl "http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD" > config.guess
sed -i 's/host_os = mingw/host_os = msys/' configure

4. Compile X264

  • Open x64 Native Tools Command Prompt for VS2019
  • Run c:/msys64/msys2_shell.cmd
  • Use the MSYS2 shell for the next steps
cd tmp/build
mkdir x264
cd x264
 
CC=cl ./../../sources/x264/configure --prefix=./../../installed --enable-shared
make -j 8
make install
mv ./../../installed/lib/libx264.dll.lib ./../../installed/lib/libx264.lib

5. Compile FFmpeg

  • Open x64 Native Tools Command Prompt for VS2019
  • Run c:/msys64/msys2_shell.cmd
  • Use the MSYS2 shell for the next steps
cd tmp/build
mkdir ffmpeg
cd ffmpeg
 
export CC=cl
 
./../../sources/ffmpeg/configure 
             --prefix=./../../installed 
             --toolchain=msvc 
             --arch=x86_64 
             --enable-yasm  
             --enable-asm 
             --enable-shared 
             --disable-static 
             --disable-programs 
             --enable-avresample 
             --enable-libx264 
             --enable-gpl 
             --extra-ldflags="-LIBPATH:./../../installed/lib/" 
             --extra-cflags="-I./../../installed/include/"
 
make V=1 -j 8
 
make install

..or as a oneliner

CC=cl ./../../sources/ffmpeg/configure --prefix=./../../installed --toolchain=msvc --arch=x86_64 --enable-yasm --enable-asm --enable-shared --disable-static --disable-programs --enable-avresample --enable-libx264  --enable-gpl  --extra-ldflags="-LIBPATH:./../../installed/lib" --extra-cflags="-I./../../installed/include/"

  • NAT Types
    This is so exciting, in this article I dive into some of the different ways a NAT device translates addresses which is important for peer-to-peer connections.


  • Building Cabinets
    In this post I dive into the design and construction of a cabinet with an interact LED strip. I also explain how I dynamically change the colors of the LEDs over TCP/UDP.


  • Compiling GStreamer from source on Windows
    How to compile GStreamer on Windows from Source using Visual Studio 2019 and the meson build system.


  • Debugging CMake Issues
    In this post I explain a process you can follow to debug issues with CMake by focusing on a specific target and making the output verbose.


  • Dual Boot Arch Linux and Windows 10
    How to install Arch Linux and Windows 10 Pro as dual boot. A step by step tutorial how to create bootable installers, partition and setup a dual boot menu.


  • Mindset Updated Edition, Carol S. Dweck (Book Notes)
    Paragraphs I marked from the book «Mindset» from Carol S. Dweck.


  • How to setup a self-hosted Unifi NVR with Arch Linux
    A step by step HOW-TO that explain show to setup a Unifi Video Controller with an NFS share with Arch Linux.


  • Blender 2.8 How to use Transparent Textures
    Follow this node setup when you want to use an image with transparency as a «sticker».


  • Compiling FFmpeg with X264 on Windows 10 using MSVC
    A couple of steps to compile FFmpeg on Windows using MSVC.


  • Blender 2.8 OpenGL Buffer Exporter
    The following Blender script creates a [name].h and [name].cpp for the selected object and stores the positions, normals and UVs.


  • Blender 2.8 Baking lightmaps
    Light maps are a cheap way to add a lot of realism to you static scenes and have been used forever.


  • Blender 2.8 Tips and Tricks
    Use Environment Map only for reflections; create a floor plane for a Product Render, diffuse texture for roughness and more!


  • Setting up a Bluetooth Headset on Arch Linux
    Learn how to setup a Sennheiser PXC 550 Bluetooth headset on Arch Linux.


  • Compiling x264 on Windows with MSVC
    Compile the excellent x264 source on Windows using MSYS2 and MSVC.


  • C/C++ Snippets
    Is a number divisible by four?


  • Reading Chunks from a Buffer
    Some thoughts on reading bytes from a file; handy for reading NALs.


  • Handy Bash Commands
    Bash scripts: removing white space, lowercase filenames, backup using tar, etc.


  • Building a zero copy parser
    Simple solution to parse data in a pretty performant way. Used this for a RTSP protocol parser.


  • Kalman Filter
    A very simple yet powerful filter which works great when you have to smooth noisy data. Used for the Nike Rise 2.0 project.


  • Saving pixel data using libpng
    Do you have raw RGBA data that you want to save? Use this snippet to save it into a PNG file.


  • Compile Apache, PHP and MySQL on Mac 10.10
    Setup you own PHP, MySQL and Apache and with virtual document roots.


  • Fast Pixel Transfers with Pixel Buffer Objects
    Using Pixel Buffer Objects (PBO) for fast asynchronous data transfers and OpenGL.


  • High Resolution Timer function in C/C++
    Wait…… wait.. fast high resolution timer funtions (Windows, Linux, Mac)


  • Rendering text with Pango, Cairo and Freetype
    My never ending obsession with font rendering. A complex beast to do well. Use Pango and FreeType for the heavy lifting.


  • Fast OpenGL blur shader
    Make things look blurry … and fast using this OpenGL blur shader.


  • Spherical Environment Mapping with OpenGL
    An old trick to get great lighting effects using Environment Maps and OpenGL.


  • Using OpenSSL with memory BIOs
    OpenSSL is a great library with lots of abstractions. In this post I discuss how to break some of these abstractions and use your own memory buffers.


  • Attributeless Vertex Shader with OpenGL
    A simple way to render a fullscreen quad without a vertex buffer with OpenGL.


  • Circular Image Selector
    Some thoughts on a different way to select images from a huge collection in a compact UI.


  • Decoding H264 and YUV420P playback
    Using libav to demux and playback with OpenGL.


  • Fast Fourier Transform
    Analyse your audio using the Fastest Fourier Transform in the West.


  • OpenGL Rim Shader
    Pretty glowy edges using a GLSL rim shader.


  • Rendering The Depth Buffer
    Render the non-linear OpenGL Depth Buffer.


  • Delaunay Triangulation
    Do you need to triangulate some shape: use the “Triangle” library.


  • RapidXML
    RapidXML is a versatile and fast XML parser with a simple API. Check out these examples.


  • Git Snippets
    Some simple GIT snippets; added here to remind myself.


  • Basic Shading With OpenGL
    A couple of basic GLSL shaders with explanation.


  • Open Source Libraries For Creative Coding
    Collection of great open source libraries for you creative programming projects.


  • Bouncing particle effect
    Snippet that can be used to create a bouncy particle effect; basic, effective, simple but nice.


  • OpenGL Instanced Rendering
    Want to render thousands and thousands of objects? Use OpenGL instanced rendering. The solution…the only solution.


  • Mapping a texture on a disc
    Ever heard about projective interpolation related to texture mapping? Learn about this intertesting issue with OpenGL and texture mapping.


  • Download HTML page using CURL
    When you want a quick solution to perform a HTTP(S) request CURL is always a quick an simple solution. Check out this example code.


  • Height Field Simulation on GPU
    Although not a Navier-Stokes implementation … still a very nice and enjoyable effect.


  • OpenCV
    Optical Flow: when doing anything with tracking you’ve probably heard of it. See this simple example code using OpenCV and OpenGL.


  • Some notes on OpenGL
    FBOs and Depth Testing, using different Attachment Points, a YUV420p shader, …


  • Math
    Meaning of the Dot Product in 3D graphics, calculating a perpendicular vector using Sam Hocevar’s solution, orientation matrix and more.


  • Gists to remember
    Some gists that I want to remember, often use, etc…


  • Reverse SSH
    Do you want to login, into a remote PC but the remote PC is behind a firewall? Then use this simple reverse SSH trick which doesn’t require changing your firewall rules.


  • Working Set
    Having issues with your compiler? Or during linking? Check these common issues and their solutions. I also list several tools that you can use to get a some useful info.


  • Consumer + Producer model with libuv
    Example of a common Multi Threaded Consumer/Producer Model using LibUV.


  • Parsing binary data
    Learn about the basic of a binary protocol and how to create one easily yourself.


  • C++ file operation snippets
    Reading a file into a string, vector, checking the file size, change to a position, etc. A collection of C++ file operation snippets.


  • Importance of blur with image gradients
    Do you want to experiment with OpenGL and aligning Brush Strokes along Image Gradients? Then check out this post about the importance of blurring.


  • Real-time oil painting with openGL
    Code snippet for fake «oil painting» effect with OpenGL using instanced rendering.


  • x264 encoder
    Basic example on how to use libx264 to encode image data using libav


  • Generative helix with openGL
    Screenshots of a project I worked on with that generates a DNA helix.


  • Mini test with vector field
    Screenshots while experimenting with a vector field; nothing much to see here.


  • Protractor gesture recognizer
    Testing the amazing One Dollar $1 gesture recognizer. The simplest and very good gesture recognizer.


  • Hair simulation
    Example code that implements the «Fast Simulation of Inextensible Hair and Fur» paper from M. Müller, T.Y. Kim and N.Chentanez.


  • Some glitch screenshots
    Glitch screenshots.


  • Working on video installation
    Screenshots of some experiments of a video installation.


  • Generative meshes
    I enjoy creating physics based simulations and render them on high res. Here are some experiments I did a time ago.


  • Converting video/audio using avconv
    Examples that show you how to use avconv to manipulate video and audio files.


  • Auto start terminal app on mac
    Automatically start you application whe Mac boots and make sure that it restarts your app when it exists. Handy for interactive installations.


  • Export blender object to simple file format
    Export the selected object in Blender into a .h and .cpp file that prepresents the buffer.

  • Installing FFMPEG from the source in window platform is easy as you do for other window application. Here is the complete instructios how to build FFMPEG in windows. To install FFMPEG on windows you need to install third party MinGW and MSys library that is compatible with GCC. This library is required to build ffmpeg in windows and support shell to run commands.

    Download MinGW and MSys

    MinGW: MinGW Direct download link
    MSys: MSys Direct download link
    SF Link: Sourceforge MinGW MSys Package Download Page
    FFMPEG: FFMPEG Download fully patched version

    ffmpeg mingw msys compile build

    Building FFMPEG

    It is time to install ffmpeg. Extract downloaded ffmpeg archive in c: folder. If you have not downloaded yet please download now then run MSys.bat file from C:msys1.0 folder. This location will be depend on you MinGW and MSys installation. In the command prompt run the following commands:

    $ cd c:/ffmpeg-0.4.7

    $ ./configure –extra-cflags=”-mno-cygwin -mms-bitfields” –extra-ldflags=”-Wl,–add-stdcall-alias” –enable-mingw32 –enable-shared –disable-a52 –disable-pp –disable-ffserver –disable-ffplay
    $ make

    Written by Bala Krishna

    Bala Krishna is web developer and occasional blogger from Bhopal, MP, India. He like to share idea, issue he face while working with the code.

    27 October 2017

    So I was trying to create some 10-bit test HEVC content with ffmpeg and ran into the following error:

    ffmpeg -i "input.mkv" -c:v libx265 -preset slow -crf 18 -pix_fmt yuv420p10le -c:a copy -y output_10bit.mkv
    
    ...
    
    Incompatible pixel format 'yuv420p10le' for codec 'libx265', auto-selecting format 'yuv420p'
    

    I discovered that by default — most ffmpeg builds include only 8-bit support for HEVC encoding with libx265.

    Certainly, you can get builds that already enable 10 or even 12-bit support — but I’m usually a glutton for punishment so I thought I would see how hard it was to just build it manually.

    Here are the exact steps I did to build both ffmpeg and libx265 with Visual Studio 2017 on Windows. Some of the steps will also detail some of the errors I ran into along the way — in case someone else runs into trouble, hopefully then it will show how to overcome any future hurdles.

    Note: This guide will only build the 64-bit versions, but you should be able to adjust for 32-bit.

    Build Tools

    • git — to get the ffmpeg source code
    • TortoiseHg — to get the x265 source code
    • Visual Studio 2017 Community Edition (you can probably get most versions 2015 and newer to work)
      • When installing VS 2017 — make sure you select the options for Desktop development with C++ so the C++ compiler and tools are installed.
    • CMAKE 3.xx
    • YASM
      • Download YASM 64-bit and copy to C:toolsyasm
      • Rename yasm-1.3.0-win64.exe (or whatever version) to yasm.exe
      • Add c:toolsyasm to your PATH environment variable
    • NASM (x265 v2.6 and older will use YASM, new versions will use NASM)
      • Download NASM 2.13 or newer to C:toolsnasm
      • Add c:toolsnasm to your PATH environment variable
    • Msys2
      • Download Msys2 installer for 64-bit and install to C:toolsmsys64
      • With a text editor, open the file C:toolsmsys64msys2_shell.cmd and un-comment the line

        rem set MSYS2_PATH_TYPE=inherit
        

        This is done so msys2 can use your existing PATH environment variable. (thanks to Scott Davies for pointing this out)

      • Now run c:Toolsmsys64msys2_shell.cmd. When the msys2 shell opens — use pacman to install the following:

        pacman -S gcc
        pacman -S diffutils
        pacman -S make
        pacman -S pkg-config
        pacman -S autoconf
        
      • Close the msys2 shell for now — we’ll relaunch later from a Visual Studio command prompt

    Build libx265 for 10-bit support

    1. Download the x265 source code

      Create the directory c:third_party and cd from a command prompt to it. Run the command:

      hg clone https://bitbucket.org/multicoreware/x265
      
    2. Navigate to third_partyx265build. Find the directory that matches the VC compiler you want to use. It is likely there will not be one matching the newest version of Visual Studio, so use the latest one available (In my case it was vc12-x86_64)

      Using a text editor, open make-solutions.bat. Change the generator command to match the version of VS you want to use. I’m using 2017, so my command is:

      cmake -G "Visual Studio 15 Win64" ....source && cmake-gui ....source
      

      Update 12/9/2017 — libx265 should now have a corresponding make-solutions.bat file for Visual Studio 2017. This step is no longer required

    3. Run the make-solutions.bat — during the processing, the CMake GUI will open with properties highlighted red.
      • Check the HIGH_BIT_DEPTH for 10-bit
      • Set the CMAKE_INSTALL_PREFIX to a directory the x265 lib, headers, and importantly the pkg-config .pc file will be installed to
      • Verify the NASM_EXECUTABLE property is pointing the location where you installed NASM

        alt text

    4. Press Configure
      • Another property called MAIN12 will probably get highlighted in red. This is for 12-bit support (if you want that check it).
      • Press Configure again
      • Press Generate
    5. Open the x265.sln in Visual Studio — change the build type to Release and the Arch to x64

    6. Change the C++ runtime to use static CRT (/MT) rather than the default (/MD) to match ffmpeg

      This should be done for the cli, common, and encoder projects.

    7. Build the ALL_BUILD project.

    8. Build the INSTALL project — this is important for building ffmpeg next

    9. Navigate to the location used in the CMAKE_INSTALL_PREFIX property above. Verify you have bin, include and lib folders.

    Build ffmpeg with custom x265 build from above

    1. Download the ffmpeg source code

      Create the directory c:third_partyffmpeg and cd from a command prompt to it. Run the command:

      git clone https://git.ffmpeg.org/ffmpeg.git ffmpeg
      

      This will result in the ffmpeg source tree located at c:third_partyffmpegffmpeg which will be handy for an out-of-tree build

    2. Create the directory c:third_partyffmpegffbuild

    3. Open a VS command prompt — I used the x64 Native Tools Command Prompt for VS 2017

    4. Change the directory — cd to c:toolsmsys64

    5. Run the msys2_shell.cmd for msys2

    6. Verify our x265 build with pkg-config

      pkg-config --exists --print-errors x265
      

      This should fail with an error similar to the following, since we haven’t told pkg-config where our x265 is.

      Package x265 was not found in the pkg-config search path.
      Perhaps you should add the directory containing `x265.pc'
      to the PKG_CONFIG_PATH environment variable
      No package 'x265' found
      

      Add the x265.pc install location to the PKG_CONFIG_PATH environment variable

      PKG_CONFIG_PATH=$PKG_CONFIG_PATH:/c/x265/lib/pkgconfig
      

      Run the verify command again — you should get no error messages

      pkg-config --exists --print-errors x265
      
    7. Configure ffmpeg for a build.

      cd /c/third_party/ffmpeg/ffbuild/
      

      There are many different ways to build ffmpeg — I’m doing the bare minimum here to get a ffmpeg build that can encode 10-bit x265:

      ../ffmpeg/configure --toolchain=msvc prefix="win-build" 
      --pkg-config-flags="--static" 
      --disable-shared 
      --enable-libx265 
      --enable-gpl 
      --enable-asm 
      --enable-x86asm
      

      If you’re following this far, the above command should fail :(

      ERROR: x265 not found using pkg-config
      

      We already verified that pkg_config could locate our x265 above, but the ffmpeg configure script is complaining …

      Open the c:third_partyffmpegffbuildffbuildffbuildconfig.log and scroll to the bottom. You should see an error something like:

      LINK : fatal error LNK1181: cannot open input file 'x265.lib'
      ERROR: x265 not found using pkg-config
      

      Navigate to C:x265lib. The x265 build from above created a static lib named x265-static.lib … rename it to x265.lib

      I’m pointing this failure out because often when building ffmpeg you will need to refer to the config.log when there is a problem

      Run the ffmpeg configure command again — this time it should be successful.

    8. Build and install ffmpeg

      make
      make install
      
    9. Your fresh ffmpeg build should be at c:third_partyffmpegffbuildwin-build

    Transcode some content to 10-bit HEVC

    1. Create a test clip with something like:

      ffmpeg -i "input.mkv" -c:v libx265 -preset slow -crf 18 -pix_fmt yuv420p10le -c:a copy -y output_10bit.mkv
      
    2. Verify the video stream in the output file is 10-bit (we’re looking for confirmation the yuv420p10le pixel format was selected)

      ffmpeg -i "output_10bit.mkv"
            
      ... 
            
      Stream #0:0(eng): Video: hevc (Main 10), yuv420p10le(tv, progressive), 1280x720 [SAR 1:1 DAR 16:9], 59.94 fps, 59.94 tbr, 1k tbn, 59.94 tbc      
            
      

    Like this post? Please share to your friends:
  • How to boot windows from usb
  • How to boot windows from grub
  • How to boot to windows 10 safe mode boot
  • How to block windows 10 update
  • How to block site in windows