Error libx264 not found

I follow this installation guide. At step 3 (Install Dependencies): sudo ./licode/scripts/installUbuntuDeps.sh in terminal But while compiling it throws error libx264 not found Why I got this e...

It happens because you are compiling libav with --enable-libx264 which would need the libx264 headers to complete. It fails at the configure phase with:

configure: error: libx264 not found

This can be fixed easily installing the needed headers package libx264-dev which should be done with sudo apt-get install yasm libvpx. libx264. but for some reason it doesn’t for you:

sudo apt-get install yasm libvpx. libx264.
Reading package lists... Done
Building dependency tree       
Reading state information... Done
Note, selecting 'libvpx-doc' for regex 'libvpx.'
Note, selecting 'libvpx1-dbg' for regex 'libvpx.'
Note, selecting 'libvpx-dev' for regex 'libvpx.'
Note, selecting 'libvpx1' for regex 'libvpx.'
Note, selecting 'libx264-133' for regex 'libx264.'
Note, selecting 'libx264-142' for regex 'libx264.'
Note, selecting 'libx264-dev' for regex 'libx264.'
libvpx-dev is already the newest version.
libvpx1 is already the newest version.
libvpx1 set to manually installed.
yasm is already the newest version.
libx264-142 is already the newest version.
libx264-142 set to manually installed.
libx264-dev is already the newest version.
The following NEW packages will be installed:
  libvpx-doc libvpx1-dbg
0 upgraded, 2 newly installed, 0 to remove and 24 not upgraded.
Need to get 1,613 kB of archives.
After this operation, 8,027 kB of additional disk space will be used.
Do you want to continue? [Y/n] n
Abort.

I needed to install ffmpeg with libx264 support for enabling H.264 encoding . I installed libx264 successfully using the below script with toolchains available in android-ndk-r9d .

 #!/bin/bash
 NDK=~/android-ndk-r9d
 SYSROOT=$NDK/platforms/android-8/arch-arm/
 TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64
 function build_one
 {
 ./configure 
 --cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- 
 --sysroot="$SYSROOT" 
 --host=arm-linux 
 --enable-pic 
 --enable-shared 
 --disable-cli
 make clean
 make
 make install
 }
 build_one 

Now I wanted to build ffmpeg with libx264 support . I used the below script with —enable-libx264 , —enable-nonfree , —enable-gpl options as in the below script .

#!/bin/bash
NDK=~/android-ndk-r9d
SYSROOT=$NDK/platforms/android-8/arch-arm/
TOOLCHAIN=$NDK/toolchains/arm-linux-androideabi-4.6/prebuilt/linux-x86_64
function build_one
{
./configure 
--prefix=$PREFIX 
--enable-shared 
--enable-nonfree 
--enable-gpl 
--enable-libx264 
--disable-doc 
--disable-ffmpeg 
--disable-ffplay 
--disable-ffprobe 
--disable-ffserver 
--disable-avdevice 
--disable-doc 
--disable-symver 
--cross-prefix=$TOOLCHAIN/bin/arm-linux-androideabi- 
--target-os=linux 
--arch=arm 
--enable-cross-compile 
--sysroot=$SYSROOT 
--extra-cflags="-Os -fpic $ADDI_CFLAGS" 
--extra-ldflags="$ADDI_LDFLAGS" 
$ADDITIONAL_CONFIGURE_FLAG
make clean
make
make install
}
CPU=arm
PREFIX=$(pwd)/android/$CPU
ADDI_CFLAGS="-marm"
build_one

But when I run the script I’m getting error «ERROR: libx264 not found» .

I suppose ffmpeg is not able to figure out the installed location of libx264 . After libx264 installation I have libx264.so file in /usr/local/lib executable at /usr/local/bin and header files at /usr/local/include directories .

What all changes do I need to make to the ffmpeg build script in-order to make it detect libx264?

Note : I am using Ubuntu 12.04(64 bit) for cross compiling .

ffmpeg и x264

FFmpeg — это универсальный инструмент для кодирования и декодирования множества видео и аудио форматов, хотя FFmpeg и x264 есть в официальных репозитариях различных дистрибутивов, иногда возникает необходимость собирать эти пакеты самостоятельно. Дело в том, что FFmpeg из Ubuntu не имеет некоторых кодеков, декодеров и не поддерживает некоторые форматы. К тому же, сами вы соберёте более свежую версию, где будут доступны последние наработки программистов.

Данная инструкция подразумевает, что у вас Ubuntu LTS (10.04) или 10.10.

Подготовительный этап

Для начала потребуется удалить некоторые установленные пакеты и установить необходимые зависимости.

Первым делом удаляем x264, libx264-dev и ffmpeg, если таковые установлены:

sudo apt-get remove ffmpeg x264 libx264-dev

Затем, устанавливаем необходимые для последующей сборки зависимости. Репозитарии universe и multiverse должны быть подключены!

sudo apt-get update
sudo apt-get install build-essential subversion git-core checkinstall yasm texi2html 
 libfaac-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev 
 libtheora-dev libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev lib1g-dev

Установка x264

Создаём в домашней директории каталог src:

mkdir ~/src

И выполняем следующее:

cd ~/src
git clone git://git.videolan.org/x264.git
cd x264
./configure
make
sudo checkinstall --pkgname=x264 --pkgversion "2:0.`grep X264_BUILD x264.h -m1 | 
 cut -d' ' -f3`.`git rev-list HEAD | wc -l`+git`git rev-list HEAD -n 1 | 
 head -c 7`" --backup=no --deldoc=yes --fstrans=no --default

После этих действий будет собран и установлен пакет x264, который можно будет удалить/обновить в будущем.

Установка FFmpeg

Получив исходные коды FFmpeg команда «./configure —help» позволит увидеть опции, которые можно включить или выключить. Итак, собираем и устанавливаем пакет:

cd ~/src
svn checkout svn://svn.ffmpeg.org/ffmpeg/trunk ffmpeg
cd ffmpeg
./configure --enable-gpl --enable-version3 --enable-nonfree --enable-postproc 
 --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb 
 --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis 
 --enable-libvpx --enable-libx264 --enable-libxvid --enable-x11grab
make
sudo checkinstall --pkgname=ffmpeg --pkgversion "4:SVN-r`LANG=C svn info | 
 grep Revision | awk '{ print $NF }'`" --backup=no --deldoc=yes --fstrans=no --default
hash x264 ffmpeg ffplay

Примеры использования FFmpeg и x264

Кодирование в один проход:

ffmpeg -i input.avi -acodec libfaac -ab 128k -ac 2 -vcodec libx264 -vpre slow -crf 22 -threads 0 output.mp4

Чем ниже параметр -crf, тем выше качество, но больше файл. Разумными являются значения от 18 до 28.

Двухпроходное кодирование:

ffmpeg -i input.avi -pass 1 -vcodec libx264 -vpre fast_firstpass -b 512k -bt 512k 
 -threads 0 -f rawvideo -an -y /dev/null && ffmpeg -i input.avi -pass 2 -acodec libfaac 
 -ab 128k -ac 2 -vcodec libx264 -vpre fast -b 512k -bt 512k -threads 0 output.mp4

Перекодирование для iPod (640×480):

ffmpeg -i input.avi -acodec libfaac -aq 100 -ac 2 -vcodec libx264 -vpre slow 
 -vpre ipod640 -crf 26 -map_meta_data 0:0 -vf scale=640:-1 -threads 0 output.mp4

Обновление FFmpeg и x264

Удаляем ранее установленные пакеты:

sudo apt-get remove ffmpeg x264 libx264-dev

Обновляем x264:

cd ~/src/x264
make distclean
git pull

Обновляем FFmpeg:

cd ~/src/ffmpeg
make distclean
svn update

В обоих случаях повторяем процедуру установки FFmpeg и x264, как было описано ранее, только с места «./configure ля-ля-ля…»

Отмена всех изменений, проделанных по данной инструкции

sudo apt-get remove x264 ffmpeg build-essential subversion git-core 
 checkinstall yasm texi2html libfaac-dev libmp3lame-dev libsdl1.2-dev libtheora-dev 
 libvorbis-dev libvpx-dev libx11-dev libxfixes-dev libxvidcore-dev zlib1g-dev

rm -rf ~/src

Источник: ubuntuforums.org

CMD Run:

D:PublicLibvcpkg>vcpkg install ffmpeg[gpl,nonfree,version3,mp3lame,fdk-aac,x264,x265,iconv,bzip2,zlib]:x64-windows

My-Computer

D:PublicLibvcpkg>vcpkg list
...
...
x264:x64-windows                                   157-303c484ec... x264 is a free software library and application ...
x265:x64-windows                                   3.4              x265 is a H.265 / HEVC video encoder application...
zlib:x64-windows                                   1.2.11#9         A compression library

RUN Result:

D:PublicLibvcpkg>vcpkg install ffmpeg[gpl,nonfree,version3,mp3lame,fdk-aac,x264,x265,iconv,bzip2,zlib]:x64-windows
Computing installation plan…
The following packages will be built and installed:
ffmpeg[avcodec,avdevice,avfilter,avformat,avresample,bzip2,core,fdk-aac,gpl,iconv,mp3lame,nonfree,postproc,swresample,swscale,version3,x264,x265,zlib]:x64-windows
Detecting compiler hash for triplet x64-windows…
Starting package 1/1: ffmpeg:x64-windows
Building package ffmpeg[avcodec,avdevice,avfilter,avformat,avresample,bzip2,core,fdk-aac,gpl,iconv,mp3lame,nonfree,postproc,swresample,swscale,version3,x264,x265,zlib]:x64-windows…
Could not locate cached archive: C:UsersmypoiAppDataLocalvcpkg/archivesabab72643f845c86b4b5abe5d90fd16fe485904f51.zip
— Using cached D:/PublicLib/vcpkg/downloads/ffmpeg-ffmpeg-n4.2.tar.gz
— Cleaning sources at D:/PublicLib/vcpkg/buildtrees/ffmpeg/src/n4.2-2f6d2343f6.clean. Use —editable to skip cleaning for the packages you specify.
— Extracting source D:/PublicLib/vcpkg/downloads/ffmpeg-ffmpeg-n4.2.tar.gz
— Applying patch 0001-create-lib-libraries.patch
— Applying patch 0003-fix-windowsinclude.patch
— Applying patch 0004-fix-debug-build.patch
— Applying patch 0005-fix-libvpx-linking.patch
— Applying patch 0006-fix-StaticFeatures.patch
— Applying patch 0007-fix-lib-naming.patch
— Applying patch 0008-Fix-wavpack-detection.patch
— Applying patch 0009-Fix-fdk-detection.patch
— Applying patch 0010-Fix-x264-detection.patch
— Applying patch 0011-Fix-x265-detection.patch
— Applying patch 0012-Fix-ssl-110-detection.patch
— Using source at D:/PublicLib/vcpkg/buildtrees/ffmpeg/src/n4.2-2f6d2343f6.clean
— Acquiring MSYS Packages from D:/PublicLib/vcpkg/downloads/tools/msys2-20200812…
— Acquiring MSYS Packages… OK
— Building Options: —enable-asm —enable-yasm —disable-doc —enable-debug —enable-runtime-cpudetect —enable-nonfree —enable-gpl —enable-version3 —disable-ffmpeg —disable-ffplay —disable-ffprobe —enable-avcodec —enable-avdevice —enable-avformat —enable-avfilter —enable-postproc —enable-swresample —enable-swscale —enable-avresample —disable-avisynth —enable-bzlib —enable-iconv —enable-libfdk-aac —disable-lzma —enable-libmp3lame —disable-cuda —disable-nvenc —disable-nvdec —disable-cuvid —disable-opencl —disable-openssl —disable-libopus —disable-sdl2 —disable-libsnappy —disable-libsoxr —disable-libspeex —disable-libtheora —disable-libvorbis —disable-libvpx —disable-libwavpack —enable-libx264 —enable-libx265 —enable-zlib —disable-static —enable-shared —extra-cflags=-DHAVE_UNISTD_H=0
— Building Release Options: —extra-cflags=-MD —extra-cxxflags=-MD
— Building ffmpeg for Release
CMake Error at scripts/cmake/vcpkg_execute_required_process.cmake:72 (message):
Command failed: D:/PublicLib/vcpkg/downloads/tools/msys2-20200812/msys64/usr/bin/bash.exe —noprofile —norc D:/PublicLib/vcpkg/ports/ffmpegbuild.sh D:/PublicLib/vcpkg/buildtrees/ffmpeg/x64-windows-rel D:/PublicLib/vcpkg/buildtrees/ffmpeg/src/n4.2-2f6d2343f6.clean D:/PublicLib/vcpkg/packages/ffmpeg_x64-windows «—enable-asm —enable-yasm —disable-doc —enable-debug —enable-runtime-cpudetect —enable-nonfree —enable-gpl —enable-version3 —disable-ffmpeg —disable-ffplay —disable-ffprobe —enable-avcodec —enable-avdevice —enable-avformat —enable-avfilter —enable-postproc —enable-swresample —enable-swscale —enable-avresample —disable-avisynth —enable-bzlib —enable-iconv —enable-libfdk-aac —disable-lzma —enable-libmp3lame —disable-cuda —disable-nvenc —disable-nvdec —disable-cuvid —disable-opencl —disable-openssl —disable-libopus —disable-sdl2 —disable-libsnappy —disable-libsoxr —disable-libspeex —disable-libtheora —disable-libvorbis —disable-libvpx —disable-libwavpack —enable-libx264 —enable-libx265 —enable-zlib —disable-static —enable-shared —extra-cflags=-DHAVE_UNISTD_H=0 —extra-cflags=-MD —extra-cxxflags=-MD»
Working Directory: D:/PublicLib/vcpkg/buildtrees/ffmpeg/x64-windows-rel
Error code: 1
See logs for more information:
D:PublicLibvcpkgbuildtreesffmpegbuild-x64-windows-rel-out.log

Call Stack (most recent call first):
ports/ffmpeg/portfile.cmake:394 (vcpkg_execute_required_process)
scripts/ports.cmake:79 (include)

Error: Building package ffmpeg:x64-windows failed with: BUILD_FAILED
Please ensure you’re using the latest portfiles with .vcpkg update, then
submit an issue at https://github.com/Microsoft/vcpkg/issues including:
Package: ffmpeg:x64-windows
Vcpkg version: 2020.06.15-nohash

Log:

build-x64-windows-rel-out.log

=== CONFIGURING ===
ERROR: libx264 not found

If you think configure made a mistake, make sure you are using the latest
version from Git.  If the latest version fails, report the problem to the
ffmpeg-user@ffmpeg.org mailing list or IRC #ffmpeg on irc.freenode.net.
Include the log file "ffbuild/config.log" produced by configure as this will help
solve the problem.

image
Доброго времени суток.
Многим web-программистам рано или поздно нужно работать с видео. Такая задача возникла и у меня.
В Интернете есть много статей на форумах и блогах, как на русскоязычных, так и на зарубежных сайтах. Но, проделавши, так же как и предлагалось в инструкциях — результата ожидаемого не дало. Что и послужило поводом для этой статьи. Думаю, она поможет

таким же как и я

многим начинающим.

Приступим

Все производилось под рутом на машине с Ubuntu 11.04 (Natty Narwhal).

root@r2d2:~# uname -a
Linux r2d2 2.6.35-30-generic #57-Ubuntu SMP Tue Aug 9 18:00:33 UTC 2011 i686 GNU/Linux

Сначала удалим старое установленное, если оно присутствует

root@r2d2:~# apt-get remove ffmpeg x264 libx264-dev

Обновляем список пакетов

root@r2d2:~# apt-get update && apt-get upgrade

Устанавливаем нужное

root@r2d2:~# apt-get install build-essential checkinstall git git-core libfaac-dev libfaad-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libva-dev libvdpau-dev libvorbis-dev libx11-dev libxfixes-dev libxvidcore-dev subversion texi2html yasm zlib1g-dev libavcodec52 mencoder

Устанавливаем библиотеку для кодирования видеопотоков H.264

Почитать подробнее можно тут и тут.

root@r2d2:~# git clone git://git.videolan.org/x264.git
root@r2d2:~# cd x264
root@r2d2:~/x264# ./configure --enable-shared 

Тут нужно сделать отступление. При конфигурировании x264 БЕЗ параметра --enable-shared библиотека будет инсталлироваться в каталог по умолчанию (у меня это /usr/local/bin) и при запуске ffmpeg будет выдавать ошибку о неизвестном местоположении библиотеки libx264:
ERROR: libx264 not found

С параметром --enable-shared результат после команды checkinstall будет следующим:

install -d /usr/local/bin
install x264 /usr/local/bin
install -d /usr/local/include
install -d /usr/local/lib
install -d /usr/local/lib/pkgconfig
install -m 644 x264.h /usr/local/include
install -m 644 x264_config.h /usr/local/include
install -m 644 x264.pc /usr/local/lib/pkgconfig
ln -f -s libx264.so.116 /usr/local/lib/libx264.so
install -m 755 libx264.so.116 /usr/local/lib

При установке на Debian также были проблемы с библиотекой libx264.
Помог параметр --prefix=/shared при конфигурировании x264.

root@r2d2:~/x264# make
root@r2d2:~/x264# checkinstall -fstrans=no -install=yes -pkgname=x264 -pkgversion «1:0.svn`date +%Y%m%d`« -default

Установка ffmpeg

Почитать подробнее можно тут и тут.

root@r2d2:~# svn checkout svn://svn.ffmpeg.org/ffmpeg/trunk ffmpeg
root@r2d2:~# cd ffmpeg
root@r2d2:~# ./configure --enable-gpl --enable-version3 --enable-nonfree --enable-postproc --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis --enable-libx264 --enable-libxvid --enable-x11grab
root@r2d2:~# make
root@r2d2:~# checkinstall -fstrans=no -install=yes -pkgname=ffmpeg -pkgversion «4:0.5+svn`date +%Y%m%d`« -default

В результате имеем:

root@r2d2:~# x264 --version
x264 0.116.2074 2641b9e
built on Sep  6 2011, gcc: 4.4.5
configuration: --bit-depth=8
x264 license: GPL version 2 or later

root@r2d2:~# ffmpeg -version
FFmpeg version SVN-r26402, Copyright (c) 2000-2011 the FFmpeg developers
  built on Sep  6 2011 09:26:49 with gcc 4.4.5
  configuration: --enable-gpl --enable-version3 --enable-nonfree --enable-postproc --enable-libfaac --enable-libmp3lame --enable-libopencore-amrnb --enable-libopencore-amrwb --enable-libtheora --enable-libvorbis --enable-libx264 --enable-libxvid --enable-x11grab
libavutil     50.36. 0 / 50.36. 0
libavcore      0.16. 1 /  0.16. 1
libavcodec    52.108. 0 / 52.108. 0
libavformat   52.93. 0 / 52.93. 0
libavdevice   52. 2. 3 / 52. 2. 3
libavfilter    1.74. 0 /  1.74. 0
libswscale     0.12. 0 /  0.12. 0
libpostproc   51. 2. 0 / 51. 2. 0
FFmpeg SVN-r26402
libavutil     50.36. 0 / 50.36. 0
libavcore      0.16. 1 /  0.16. 1
libavcodec    52.108. 0 / 52.108. 0
libavformat   52.93. 0 / 52.93. 0
libavdevice   52. 2. 3 / 52. 2. 3
libavfilter    1.74. 0 /  1.74. 0
libswscale     0.12. 0 /  0.12. 0
libpostproc   51. 2. 0 / 51. 2. 0

Теперь, если набрать в консоли

ffmpeg -threads 4 -y -i "video.avi" -vcodec libx264 -vpre "hq" -b 2000k -acodec libfaac -ar 44100 -ab 128k -ac 2 "video.flv"

на выходе получаем сконвертированый файл, который можно использовать в своих целях.

Немного о параметрах конвертации

-i — имя исходного файла;
-ar — частота дискретизации звука (должна быть кратна 11кГц);
-ab — аудио битрейт;
-ac — количество каналов звука (1 — моно, 2 — стерео);
-f — формат исходящего видео-файла;
-b — битрейт видео (30k, 200k, 512k, 1024k);
-maxrate — максимальный битрейт кодирования видеопотока (9000k);
-r — кадров в сек (FPS);
-s — размер видео в пикселях;
-fs — установить максимальный размер выходного файла;
-vpre — файл с предустановленными параметрами конвертирования (preset);
-ss 00:02:00 — смещение по времени от начала файла (position). Здесь: пропустить первые 2 мин (сдвиг в сек.). Задается в сек. или временем в формате: hh:mm:ss[.xxx];
-vframes — ограничение на количество кадров видео;
-y — перезаписать файл, если он уже существует;
-aspect — соотношение сторон(4:3, 16:9, 1.3333);
-acodec — аудио-кодек (libfaac, aac, libmp3lame);
-vcodec — видео-кодек (libx264);
-threads 0 — количество ядер в компьютере. Значения: 0 — 4. 0 — автоматически определить количество ядер процессора и использовать их в процессе работы.

ffmpeg имеет файлы с предустановленными настройками для кодирования. Они находятся в папке ffmpeg/ffpresets

root@r2d2:~/ffmpeg/ffpresets# ls -al
libx264-baseline.ffpreset
libx264-faster.ffpreset
libx264-faster_firstpass.ffpreset
libx264-fast.ffpreset
libx264-fast_firstpass.ffpreset
libx264-ipod320.ffpreset
libx264-ipod640.ffpreset
libx264-lossless_fast.ffpreset
libx264-lossless_max.ffpreset
libx264-lossless_medium.ffpreset
libx264-lossless_slower.ffpreset
libx264-lossless_slow.ffpreset
libx264-lossless_ultrafast.ffpreset
libx264-main.ffpreset
libx264-medium.ffpreset
libx264-medium_firstpass.ffpreset
libx264-placebo.ffpreset
libx264-placebo_firstpass.ffpreset
libx264-slower.ffpreset
libx264-slower_firstpass.ffpreset
libx264-slow.ffpreset
libx264-slow_firstpass.ffpreset
libx264-superfast.ffpreset
libx264-superfast_firstpass.ffpreset
libx264-ultrafast.ffpreset
libx264-ultrafast_firstpass.ffpreset
libx264-veryfast.ffpreset
libx264-veryfast_firstpass.ffpreset
libx264-veryslow.ffpreset
libx264-veryslow_firstpass.ffpreset

И после установки должны находиться в /usr/local/share/ffmpeg/. По названию файла можно догадаться, за что отвечает определенный файл. Подробнее об этих файлах можно почитать по вышеуказанным ссылкам

Файл с настройками, который используется в примерах

root@r2d2:/usr/share/ffmpeg# cat libx264-hq.ffpreset
coder=1
flags=+loop
cmp=+chroma
partitions=+parti8x8+parti4x4+partp8x8+partb8x8
me_method=umh
subq=8
me_range=16
g=250
keyint_min=25
sc_threshold=40
i_qfactor=0.71
b_strategy=2
qcomp=0.6
qmin=10
qmax=51
qdiff=4
bf=3
refs=4
directpred=3
trellis=1
flags2=+wpred+mixed_refs+dct8x8+fastpskip

Откат от всего установленного

root@r2d2:~# apt-get remove build-essential checkinstall git git-core libfaac-dev libfaad-dev libjack-jackd2-dev libmp3lame-dev libopencore-amrnb-dev libopencore-amrwb-dev libsdl1.2-dev libtheora-dev libva-dev libvdpau-dev libvorbis-dev libx11-dev libxfixes-dev libxvidcore-dev subversion texi2html yasm zlib1g-dev libavcodec52 mencoder x264 ffmpeg

Получении информации о видео с помощью PHP

Для получения информации о видео я использую немного переделаную функцию, которую нашел в этом посте.

function get_video_size($videofile) {
    define('MAX_VIDEO_WIDTH', 200);
    $vwidth = 0;
    $vheight = 0;
    $owidth = 0;
    $oheight = 0;
    $duration = array();
    $bitrate = 0;
    $audio_bitrate = 0;
    $sfrequency = 0;

    ob_start();
    passthru('ffmpeg -i "' . $videofile . '" 2>&1 | egrep -e "(Duration|Stream)"');
    $ffmpeg_output = ob_get_contents();
    ob_end_clean();

    if (sizeof($ffmpeg_output) == 0) {
        return null;
    }

    foreach (explode("n", $ffmpeg_output) as $line) {
        $ma = array();
        // get duration and video bitrate
        if (strpos($line, 'Duration:') !== false) {
            preg_match('/(?<hours>d+):(?<minutes>d+):(?<seconds>d+).(?<fractions>d+)/', $line, $ma);
            $duration = array(
                'raw' => $ma['hours'] . ':' . $ma['minutes'] . ':' . $ma['seconds'],
                'hours' => intval($ma['hours']),
                'minutes' => intval($ma['minutes']),
                'seconds' => intval($ma['seconds']),
                'fractions' => intval($ma['fractions']),
                'rawSeconds' => intval($ma['hours']) * 60 * 60 + intval($ma['minutes']) * 60 + intval($ma['seconds']) + (intval($ma['fractions']) != 0 ? 1 : 0)
            );

            preg_match('/bitrate:s(?<bitrate>d+)skb/s/', $line, $ma);
            $bitrate = $ma['bitrate'];
        }

        // get video info
        if (strpos($line, 'Video:') !== false) {
            preg_match('/Stream #(?:[0-9.]+)(?:.*): Video: (?P<videocodec>.*) (?P<width>[0-9]*)x(?P<height>[0-9]*)/', $line, $ma);
            $vheight = $oheight = $ma['width'];
            $vwidth = $owidth = $ma['height'];
        }

        // get audio info
        if (strpos($line, 'Audio:') !== false) {
            preg_match('/,s(?<sfrequency>d+)sHz,/', $line, $ma);
            $sfrequency = $ma['sfrequency'];

            preg_match('/,s(?<bitrate>d+)skb/s/', $line, $ma);
            $audio_bitrate = $ma['bitrate'];
        }
    }

    // calculate new size of the video
    if ($vwidth > MAX_VIDEO_WIDTH) {
        $coef = $vheight / $vwidth;
        $vwidth = MAX_VIDEO_WIDTH;
        $vheight = round($vwidth * $coef);
    }

    // frame size must be a multiple of 2
    $vwidth = $vwidth % 2 != 0 ? $vwidth - 1 : $vwidth;
    $vheight = $vheight % 2 != 0 ? $vheight - 1 : $vheight;

    return array(
        'width' => $vwidth,
        'height' => $vheight,
        'srcWidth' => $owidth,
        'srcHeight' => $oheight,
        'duration' => $duration,
        'bitrate' => $bitrate,
        'audioBitrate' => $audio_bitrate,
        'audioSampleFrequency' => $sfrequency
    );
}

В итоге имеем готовый пример

$ffmpeg_path = 'ffmpeg'; // Путь к ffmpeg
$in = 'ATB - Let You Go.avi'; // Входящий файл
$out = 'ATB - Let You Go.flv'; // Исходящий файл

$video = get_video_size($in);
$hq = 'hq'; // Подключаем файл с предустановленными настройками

$command = $ffmpeg_path . ' -threads 0 -y -i "' . $in . '" -vcodec libx264 -vpre "' . $hq . '" -b ' . $video['bitrate'] . 'k -s ' . $video['width'] . 'x' . $video['height'] . ' -acodec libfaac -ar ' . $video['audioSampleFrequency'] . ' -ab ' . $video['audioBitrate'] . 'k -ac 2 "' . $out . '"';
$conv = exec($command);

#3876

closed


defect


(fixed)

configure ERROR: libx264 not found

Reported by: Owned by:
Priority: normal Component: build system
Version: git-master Keywords: libx264
Cc: Blocked By:
Blocking: Reproduced by developer: no
Analyzed by developer: no

Summary of the bug:
How to reproduce:

% compile libx264 with shared libraries disabled, and then configure ffmpeg with enabled libx264 library

if i have compiled libx264 without shared librarys and I try to configure ffmpeg with libx264 then I am getting error «ERROR: libx264 not found».
I have checked config.log and saw that there is missing in tests libdl.so, I have manually changed the line in configure script and added -ldl and now I can configure with libx264 when x264 is compiled only as static. please put it on the repository.

Here is a script I found on the net, and I just recently fixed it for Ubuntu 12

#!/bin/sh
#
# Name: ffmpeg git
# Version: 0.01a
# Description: ffmpeg git compilation with libvorbis, x264, mp3 lame support
# Script_URI:

http://www.techno-blog.net

#
# Author: Nikos

###########################
##### Run some checks #####
###########################

# Check if user is root
if [ $(id -u) != «0» ]; then
echo «Erreur : Vous devez être root pour utiliser ce script, use sudo sh $0»
exit 1
fi

#############################################
##### Set some variables and functions ######
#############################################

# Directory where this script is located
BASEDIR=»$(dirname $0)»

error_out() {
echo «Could not ${1}, aborting»
exit 1
}

wrap() {
local ErrorMsg=»$1″
shift
local cmd=»$1″
shift
$cmd «$@» || error_out «$ErrorMsg»
}

# Function to install packages
install_pkgs() {
aptitude -yq=3 install «$@»
}

# Function to remove packages
remove_pkgs() {
aptitude -yq=3 remove «$@»
}

#################################
##### The magic starts here #####
#################################

# Uninstall Packages
wrap «remove libmp3lame-dev ffmpeg» remove_pkgs libmp3lame-dev ffmpeg

# Install packages
wrap «install some dependancies» install_pkgs quilt libsdl1.2-dev libogg-dev libvorbis-dev liba52-dev libdts-dev libimlib2-dev texi2html libraw1394-dev libdc1394-22-dev libtheora-dev libgsm1-dev libxvidcore-dev libfaac-dev libfaad-dev build-essential git-core checkinstall yasm texi2html libopencore-amrnb-dev libopencore-amrwb-dev libtheora-dev libvorbis-dev libx11-dev libxfixes-dev zlib1g-dev nasm

# Retrieving x264, libvorbis, mp3lame
mkdir ffmpeg_source
cd ffmpeg_source

wrap «retrieving x264 from git sources» git clone

git://git.videolan.org/x264

cd x264
wrap «set up x264 config» ./configure —enable-static —disable-opencl
wrap «compilation with 3 cores» make -j3
wrap «build install-lib-dev» make install-lib-dev
wrap «build DEB package» checkinstall —pkgname=x264 —default —pkgversion=»3:$(./version.sh | awk -F'[» ]’ ‘/POINT/{print $4″+git»$5}’)» —backup=no —deldoc=yes

cd ..
mkdir -p /usr/local/share/doc/lame
wrap «download lamemp3 source» wget

http://downloads.sourceforge.net/projec … 8.4.tar.gz

tar xzvf lame-3.98.4.tar.gz
cd lame-3.98.4
wrap «set up lamemp3» ./configure —enable-nasm —disable-shared
wrap «compilation» make
wrap «build DEB package» checkinstall —pkgname=lame-ffmpeg —pkgversion=»3.98.4″ —backup=no —default —deldoc=yes

cd ..
wrap «retrieving libvpx from git sources» git clone

http://git.chromium.org/webm/libvpx.git

cd libvpx
wrap «set up libvpx config» ./configure
wrap «compilation with 3 cores» make -j3
wrap «build DEB package» checkinstall —pkgname=libvpx —pkgversion=»$(date +%Y%m%d%H%M)-git» —backup=no —default —deldoc=yes

cd ..
wrap «retrieving ffmpeg from git sources» git clone

git://git.videolan.org/ffmpeg

cd ffmpeg
wrap «set up ffmpeg config» ./configure —enable-gpl —enable-postproc —enable-swscale —enable-pthreads —enable-x11grab —enable-libdc1394 —enable-libfaac —enable-libgsm —enable-libmp3lame —enable-libtheora —enable-libvorbis —enable-libx264 —enable-libxvid —enable-nonfree —enable-version3 —enable-libopencore-amrnb —enable-libopencore-amrwb —enable-libvpx —enable-avfilter
wrap «compilation with 3 cores» make -j3
wrap «build DEB package» checkinstall —pkgname=ffmpeg —pkgversion=»0.6.3-git» —backup=no —deldoc=yes —default
hash x264 ffmpeg ffplay ffprobe

echo «#############################»
echo «##### Mission complete! #####»
echo «#############################»

x264 seems to install fine. FFmpeg complains that it can’t find libx264 when I use makepkg and the PKGBUILDs below.  However, FFmpeg will find libx264 if:

     * —enable-shared is added to the x264 PKGBUILD, or
     * ./configure (with the same options from the FFmpeg PKGBUILD below) is run manually

This used to work for me until I upgraded the system on June 27 (x86_64). The last previous upgrade was June 10.  I can also duplicate this on a new Arch VM.

Questions
Why can FFmpeg not find a static libx264 when using makepkg?
Why does a manual FFmpeg ./configure find libx264, but makepkg does not?

To Duplicate
1. Install x264 using this PKGBUILD (adapted from x264-git, but without —enable-shared):

pkgname=x264-git
pkgver=20100605
pkgrel=1
pkgdesc="free library for encoding H264/AVC video streams"
arch=('i686' 'x86_64')
license=('GPL')
depends=('glibc')
makedepends=('git' 'yasm')
url="http://www.videolan.org/developers/x264.html"
conflicts=('x264')
provides=("x264=$pkgver")
source=()
md5sums=()

_gitroot="git://git.videolan.org/x264.git"
_gitname="x264"

build() {
  cd $srcdir
  msg "Connecting to the GIT server...."
  
  if [[ -d $srcdir/$_gitname ]] ; then
    cd $_gitname
    git pull origin
    msg "The local files are updated."
  else
    git clone $_gitroot
  fi
  
  msg "GIT checkout done"
  msg "Starting make..."
  
  rm -rf $srcdir/$_gitname-build
  git clone $srcdir/$_gitname $srcdir/$_gitname-build
  
  cd $srcdir/$_gitname-build

  ./configure --prefix=/usr || return 1
  
  make || return 1
  make DESTDIR=$pkgdir install || return 1
  
  rm -rf $srcdir/$_gitname-build
}

2. Install FFmpeg using this PKGBUILD (adapted from ffmpeg-svn, but pruned of many non-libx264 related dependencies and options):

# Contributor: raubkopierer <mail[dot]sensenmann[at]googlemail[dot]com>

pkgname=ffmpeg-svn
pkgver=23482
pkgrel=1
pkgdesc="Complete and free Internet live audio and video broadcasting solution for Linux/Unix"
arch=('i686' 'x86_64')
url="http://ffmpeg.mplayerhq.hu/"
license=('GPL')
depends=('sdl' 'zlib' 'x264-git>=20100605')
makedepends=('subversion')
provides=("ffmpeg=`date +%Y%m%d`" "qt-faststart")
conflicts=('ffmpeg')
source=()
md5sums=()

_svntrunk=svn://svn.ffmpeg.org/ffmpeg/trunk
_svnmod=ffmpeg

build() {
  cd "$srcdir"

  if [ -d $_svnmod/.svn ]; then
    (cd $_svnmod && svn up -r $pkgver)
  else
    svn co $_svntrunk --config-dir ./ -r $pkgver $_svnmod
  fi

  msg "SVN checkout done or server timeout"
  msg "Starting make..."

  rm -rf "$_svnmod-build"
  mkdir "$_svnmod-build"
  cd "$_svnmod-build"

  "$srcdir/$_svnmod/configure" 
  --prefix=/usr 
  --enable-gpl 
  --enable-libx264 
  --enable-pthreads 
  --arch=`uname -m` 
  || return 1

  make || return 1
  make doc/ff{mpeg,play,server}.1 || return 1

  make DESTDIR="$pkgdir" install || return 1
  make DESTDIR="$pkgdir" install-man || return 1

  make tools/qt-faststart || return 1
  cp -a tools/qt-faststart $pkgdir/usr/bin
}

FFmpeg should complain with ERROR: libx264 not found.  I added the config.log to pastebin.

Last edited by DrZaius (2010-07-01 17:51:22)

Понравилась статья? Поделить с друзьями:
  • Error libtool library used but libtool is undefined
  • Error libshacccg suprx is not installed
  • Error library index could not be retrieved
  • Error libmfx not found
  • Error libevent2 development libraries are not installed properly in required location