- Enable Hardware Video Acceleration (VA-API) For Firefox in Ubuntu 20.04 / 18.04 & Higher
- Verify VA-API:
- Enable VA-API in Firefox:
- Check if Hardware Video Acceleration working:
- Enable hardware acceleration on Firefox and make it faster
- Enable hardware acceleration in Firefox
- Enabling GPU acceleration in Firefox 76 under Ubuntu 20.04 with Wayland
- Prerequisites
- Tweaking Firefox
- Verification
- Аппаратное ускорение в Firefox
Enable Hardware Video Acceleration (VA-API) For Firefox in Ubuntu 20.04 / 18.04 & Higher
This tutorial shows how to enable hardware video acceleration (VA-API) for Firefox, so it uses the video card to decode/encode video to save power.
Hardware video acceleration is a computer technology to make the graphics card to encode and decode video, thus offloading the CPU to save power. And compared to CPU, GPU are normally more efficient at the job.
There are a few ways to achieve this on Ubuntu Linux, including:
- Video Acceleration API (VA-API) – an open source API developed by Intel.
- Video Decode and Presentation API for Unix (VDPAU) – open source API developed by NVIDIA.
- NVENC/NVDEC – NVIDIA’s proprietary API.
The VA-API supports Intel, AMD, and NVIDIA (via open-source Nouveau drivers) GPUs. And it is widely supported by software, such as MPV uses va-api hardware acceleration for video playback by default if available.
The VDPAU API supports both AMD and NVIDIA, but has no support in Firefox or Chromium. And while NVENC/NVDEC is used for NVIDIA GPU only, we usually use VA-API for hardware video acceleration.
Firefox pop-up video encoding/decoding via Intel GPU
Verify VA-API:
NOTE: VA-API does not work on NVIDIA via proprietary drivers as mentioned above. If you installed NVIDIA proprietary driver via ‘Additional Drivers’ utility, this will only work when you choose ‘Intel (Power Saving)’ mode in NVIDIA Prime settings.
The VA-API may work out-of-the-box in Ubuntu. You can firstly open terminal from start menu (click ‘Activities’ and search terminal).
Next install vainfo package via command:
And run it to check VA-API info:
It outputs the driver as well as supported profile. VAEntrypointVLD means decoding support for this format, VAEntrypointEncSlice means encoding support.
If the command outputs an error, you can try to install drivers via command:
- For NVIDIA nouveau and AMD, run command:
- For Gen 8+ Intel hardware, install via command:
And for old Intel hardware, install i965-va-driver instead via apt install command.
By setting the environment variable, you can choose which driver to use. For example, set “export LIBVA_DRIVER_NAME=i965” to use i965 driver. The value can also set to “nouveau” for NVIDIA, or “radeonsi” for AMDGPU.
Enable VA-API in Firefox:
Firefox added VA-API support since version 80, though it’s not enabled by default. You can enabled it manually by doing following steps one by one.
Firstly, open Firefox and go to about:config in url bar. Click on “Accept the Risk and Continue”. Then search for following keys, enable or disable them one by one:
- media.ffmpeg.vaapi.enabled set to true
- media.ffvpx.enabled set to false .
- media.rdd-vpx.enabled set to false .
- media.navigator.mediadatadecoder_vpx_enabled set to true .
- If you experience page crashes, try setting security.sandbox.content.level to 0 .
Secondly, set environment variable (for current user only). Open terminal and run command to edit profile file:
When file opens, add following lines to the end:
- (Optional) Specify va-api driver as mentioned above (replace iHD accordingly):
You can SKIP this if vainfo outputs without error!
Finally, log out and back in. Open Firefox and play a video and see result!
Check if Hardware Video Acceleration working:
During video playback, you can use top command to see CPU usage before and after enable VA-API. For Intel GPU, there’s intel_gpu_top command that monitor it continuously.
Open terminal and run command to install the tool first:
Next, run command:
Start playing video in Firefox and you’ll see the video bar is busy (above 0%) if VA-API starts working.
For AMD GPU, there’s another command line tool “radeontop” available to monitor GPU activity.
NOTE for YouTube videos, the video codec may sometimes not supported by your hardware. To workaround, try h264ify or enhanced-h264ify extension to make YouTube stream H.264 videos instead of VP8/VP9.
Источник
Enable hardware acceleration on Firefox and make it faster
On Linux, Firefox hardware acceleration is disabled by default on all distributions. The reason is about a potential security risk or a faulty implementation that does not properly support dual-GPU systems, or something more.
So, first of all, read carefully this post on Reddit, the potential security problem due to WebGL and about the Firefox hardware accelerated rendering on X11. After that, you can try to transform Firefox in a super fast web browser.
How to enable hardware acceleration in Firefox on Linux
Enable hardware acceleration in Firefox
To enable hardware acceleration in Firefox on Linux, we must enter in the advance configuration menu of the browser.
In the Firefox address bar, type this: about:config .
Looking for layers.acceleration.force-enabled and double click on it to turn the value from ‘false’ to ‘true’.
Finally, restart the browser and enjoy its new speed. Personally, I did it on my testing machine with Fedora 26 Alpha and Firefox 53 on board, and I found it really faster, especially with a lot of tabs opened.
Источник
Enabling GPU acceleration in Firefox 76 under Ubuntu 20.04 with Wayland
Firefox 76 came out yesterday, bringing to the table — amongst more widely known features — initial support for hardware acceleration of VP9-encoded videos for Wayland. Translating to human language: now you can watch YouTube videos without making your laptop fans spinning at full speed. Please note, however, the word initial there — few tweaks are gonna be required to pull the hardware acceleration off.
This guide is a compilation of tips and tweaks from various sources, like Martin Stransky’s Blog, who is one of the Firefox developers, Arch wikis (1, 2) and some Reddit threads 1
Prerequisites
First, if you have NVIDIA GPU, there’s no hope. As you probably know, there’s not so much love for NVIDIA in open-source world, and this feature is indifferent. Other than that, if you happen to have non-ancient AMD/ATI or Intel iGPU, you’re in luck.
Now, to use your GPU, you need three things: latest Firefox, VA-API support in your OS, and a Wayland-based compositor. First one is just sudo apt-get update && sudo apt-get install -y firefox . Fortunately, latter requirements comes by default with the new Ubuntu 20.04, which despite some serious controversies related to its Snap store, still seems to be most-polished distro out there.
Now regarding the compositor: Wayland is still a little experimental, “glitches ahead” and all, but I’m using it for over a week now without any major issues or annoying hiccups. On plus side, it’s much smoother than x11 and allows for 4-finger gestures for switching workspaces — just like on macOS. Your mileage may vary, of course.
To start Wayland session, simply choose “Ubuntu on Wayland” on OS login screen (gear icon in bottom-right corner). From now on, Wayland is the default, until you switch to classic, x11-based compositor.
Second thing is support for VA-API on your OS. Ubuntu comes with default CLI utility, vainfo (you can install it with sudo apt-get install vainfo ), just for the purpose of retrieving info on VA-API status. Your output should look like this:
The presence of VP9 profiles is crucial for YouTube videos.
If your output lacks this information and you still believe your GPU is able to decode video with hardware support, visit this Arch wiki for further instructions, having in mind that you use Debian-derivative OS, so commands and package names are different.
Tweaking Firefox
Next step is to tell Firefox to use Wayland. Just edit (with sudo) its /usr/share/applications/firefox.desktop file and prepend firefox executable with specific flags, so such line:
and so on; repeat that for all 3 lines containing Exec= .
Now restart Firefox and check if those flags actually work by going to about:support and checking Window protocol — its value should be wayland (or similar), not x11 . If that’s not the case, please note that Firefox downloaded directly from Mozilla website instead of installed from PPA (which translates to “not installed with apt-get «) might have trouble with using those flags you just pasted.
The last step is to enable few flags in Firefox config, so while being in the browser, go to about:config URL and enable these flags by settings them to true :
and set this one below to false :
Verification
Restart the browser. Now it’s time for one last verification that everything is correct: go to about:support and verify those params:
- Compositing should be WebRender
- WebGL 1 Driver Version should say OpenGL something something
- Window Protocol should be wayland/drm or similar
If that’s the case, you’re ready to head to YouTube and play some 4K video in fullscreen. In my case, with i7-8650u laptop, watching 4K video on 1440p external screen causes Firefox process to eat
50% CPU measured in htop (before tweaks it was between 100-150%).
Overall rendering performance should be improved, too, so scrolling should have much less latency and be much smoother, just like on Windows or macOS. Before these tweaks my Firefox 76 installation scored around 86 points in MotionMark benchmark, after applying tweaks the result was 315 points — even higher than Chromium (207), which is known to outperform Firefox severely in rendering benchmarks.
Источник
Аппаратное ускорение в Firefox
Есть ноут на Athlon 300U Установлены Ubuntu 20.10, Firefox 82
В about:config включил media.ffmpeg.vaapi.enabled и layers.acceleration.force-enabled
При проигрывании видео 1080p лис жрёт 60+% проца согласно htop
Рядом ноут на оффтопике, проц там пошустрее (i7-10750H), но то же видео грузит проц всего на 3%.
Как узнать, используется ли аппаратное ускорение в Firefox? В about:support про видео нашёл:
сначала скажи сколько ест то же видео на 300U например когда в консоле через mpv смотришь
проверил в VLC, загрузка 8% для видео 1080. Явно ускорение работает.
В Firefox есть три пути вывода картинки на экран. Basic, OpenGL и WebRender. В большинстве конфигураций под Linux автоматически выбирается Basic. Опция layers.acceleration.force-enabled принудительно включает OpenGL. А декодирование видео через VA-API реализовано только для WebRender. Принудительно его можно включить установкой опции gfx.webrender.all в true . Опцию layers.acceleration.force-enabled лучше отключить.
Проверить, какой композитор используется сейчас, можно на about:support , в строке «Compositing». Тебе нужно добиться, чтобы там было «WebRender».
Про MOZ_X11_EGL=1 выше уже упоминали. EGL тоже обязателен.
ускорение не работает.
В about:support следующие значения:
Осталась тяжёлая артиллерия. Собираешь лог:
Потом смотришь в лог на предмет строчки, содержащей «D/PlatformDecoderModule DMABUF/VA-API Got one frame output with». На остальные строки тоже стоит глянуть, особенно на содержащие «vaapi», «VAAPI» и «VA-API».
Два ядра, четыре потока.
Этот же htop показывает «четыре ядра»? Так тогда htop считает процессор полностью загруженным, когда он загружен на 400%, а не на 100%. Соответственно, 60% от 400% — это, возможно, и нормально. Ютубовский плеер на яваскирптах внутри Файрфокса крутить — это вам не шутки.
Про vaapi ничего.
Согласно vainfo, драйвер умеет h264 и VP9.
Непонятно, чего ему не хватает …
Проверил, если все настройки по умолчанию загрузка чуть-чуть больше. И chromium примерно столько же жрёт.
Попробую chromium с vaapi, вдруг заработает.
Да я не о том же.
У меня Firefox с ютубчиком жрал вообще всё, что ему позволялось жрать. С аппатарным ускорением стал жрать
15%. Если считать так, как считает htop, то насчитать можно 15*4=60.
top тоже так считает.
поржал. там должно быть переключение в нормальные проценты, или наверху должен быть инликатор который можно переключить в нормальные проценты
и да, ещё заметил, что проценты эти считаются как-то неправильно при взаимодействии с энергосбережением процессора
Так скажи ТСу, как ему проверить, в каком положении у htop этот «переключатель» и как индикатор переключать. Мне ksysguard как я хочу, так и считает.
Проверил ещё раз с опцией CPU Average в htop.
Беру видео https://www.youtube.com/watch?v=LXb3EKWsInQ в качестве 720p60 (1080 не скачивается)
Запускаю видео в VLC, CPU Average 4-5% (это все процессы в системе)
Открываю то же видео в Firefox, CPU Average 30%
Отключаю все ускорения в Firefox, CPU Average 30%
- в VLC ускорение работает
- в Firefox оно не работает либо реализовано так убого, что нет разницы, с ускорением или без него)
А чего у AMD вообще нет утилит по мониторингу?
это чё, ты нагрузку на проц с нагрузкой на asic сравниваешь?
Нету, в mesa есть встроенный мониторинг но только по графической части.
ты нагрузку на проц с нагрузкой на asic сравниваешь?
Принятие и смирение. Поздравляю. в MPV/VLC работает и ладно, а браузеры не то чтобы сверхважный софт. Меня браузерное видеоускорение даже на винде никогда не интересовало. Проигрывай > 1080p в плеерах и не парься.
видеоускорение даже на винде никогда не интересовало
а чё там интересоваться, оно просто работает. если б не работало, тогда может была бы причина интересоваться
оно просто работает. если б не работало, тогда может была бы причина интересоваться
На винде у меня не развешены индикаторы нагрузки ЦП, так что там мне на это было пофиг. Запустил игру, поиграл. Ненадолго прервался на листание браузера и снова вернулся в игру. А под линуксом «игор-то нет», большую часть времени тормозилла открыта, ютуб что-нибудь да грузит, судя по виджетам. Неприятно, но я смирился. Можно еще скармливать плееру ютубовские ссылки, а с другими сайтами это не прокатит скорее всего, нужны прямые ссылки.
Выложи куда-нибудь полный лог. Возможно там упоминаются причины в начале.
Помогло отключение media.ffvpx.enabled. Не заладилось у Лиса декодирование vp9 аппаратно, хотя видеокарта и драйвер якобы поддерживают.
видео 1080p60 занимает 20% CPU Average. Если выключить MOZ_X11_EGL, то 40% CPU Average.
В общем, для слабого проца 20% загрузки на видео 1080p60 считаю приемлемым результатом.
Тем более для оси, где графика в зачаточном состоянии (Wayland, ау)
Помогло отключение media.ffvpx.enabled. Не заладилось у Лиса декодирование vp9 аппаратно, хотя видеокарта и драйвер якобы поддерживают.
ffvpx это особая сборка ffmpeg, которую Firefox таскает с собой для VP9 и прочих кодеков, которые можно распространять без лицензионных выплат. Всё ненужное там вырезано, включая VA-API.
Попытки вернуть VA-API в ffvpx вроде как есть, но пару месяцев назад там были какие-то сложности. Не знаю, как там сейчас. Видимо, ещё не сделали.
Понятно. Могли бы разрабы использовать ffmpeg по умолчанию, раз уж он есть в системе.
А это хорошая идея. Сразу много проблем решает.
А зависит ли поддержка аппаратного декодирования в ФФ от версии ядра? Просто щас столкнулся, что на 5.4 хардварь работает, а на 4.19 нет. На одной системе. При этом vlc/mpv на обеих версиях используют хардварь. Мониторю intel_gpu_top.
есть еще один вариант, возможно вот что еще влияет: в убунте и в арче, да и в других дистрах (рпм или слаквэйр) есть варианты (наверняка, по поводу слаки и сусе или рпм дистров не уверен, но магея и опенмандрива точно делят это дело так же) пакетов с va-api драйверами, которые по идее использует меса драйвер радеон или amdgpu. Вопрос в том что на встройке вашей может это не работать, либо до перезапуска, либо оно и у меня будет работать через жопу. Что касается VLC то с десктопом это сравнивать точно не стоит.
i965-va-driver/groovy 2.4.0-0ubuntu1 amd64 VAAPI driver for Intel G45 & HD Graphics family
i965-va-driver-shaders/groovy,now 2.4.1-1 amd64 [установлен] VAAPI driver for Intel G45 & HD Graphics family
intel-media-va-driver/groovy 20.2.0+dfsg1-1 amd64 VAAPI driver for the Intel GEN8+ Graphics family
intel-media-va-driver-non-free/groovy,now 20.2.0+ds1-1 amd64 [установлен] VAAPI driver for the Intel GEN8+ Graphics family
Для интелов да может быть такое, я сижу на апдэйт скрипте который тянет (ubuntu mainlike kernel sh git гуглить если че) 5.10.4 релизный мне, 5.11 у них релиз кандидат 1 не собрался.
Для radeon, intel, amdgpu драйверов ядро и версия mesa актуальны ну и пакетов драйверов xorg.
Для Nvidia тоже но в пределах совместимости бинарного драйвера с текущим доступным ядром (в смысле 455й который самый последний вроде какое там ядро поддерживает, но это для убунты 20.10, а так там уже вроде 500 какой то выходил).
Про intel-gpu-tools не знал, у меня Е4500 + радеон р5 230 1Гб памяти, а в е4500 lspci | grep Intel:
intel_gpu_top Failed to detect engines! (No such file or directory) (Kernel 4.16 or newer is required for i915 PMU support.)
uname -a Linux sergey-pc 5.10.4-051004-generic #202012301142 SMP Wed Dec 30 11:44:55 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux
очевидно, что при присутствии дискретной карточки от амд встройка не работает (ну или может быть работает как процессор простой)
lspci | grep Radeon 01:00.0 VGA compatible controller: Advanced Micro Devices, Inc. [AMD/ATI] Caicos [Radeon HD 6450/7450/8450 / R5 230 OEM] 01:00.1 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] Caicos HDMI Audio [Radeon HD 6450 / 7450/8450/8490 OEM / R5 230/235/235X OEM]
00:00.0 Host bridge: Intel Corporation 82P965/G965 Memory Controller Hub (rev 02) 00:01.0 PCI bridge: Intel Corporation 82P965/G965 PCI Express Root Port (rev 02) 00:1a.0 USB controller: Intel Corporation 82801H (ICH8 Family) USB UHCI Controller #4 (rev 02) 00:1a.1 USB controller: Intel Corporation 82801H (ICH8 Family) USB UHCI Controller #5 (rev 02) 00:1a.7 USB controller: Intel Corporation 82801H (ICH8 Family) USB2 EHCI Controller #2 (rev 02) 00:1b.0 Audio device: Intel Corporation 82801H (ICH8 Family) HD Audio Controller (rev 02) 00:1c.0 PCI bridge: Intel Corporation 82801H (ICH8 Family) PCI Express Port 1 (rev 02) 00:1c.4 PCI bridge: Intel Corporation 82801H (ICH8 Family) PCI Express Port 5 (rev 02) 00:1c.5 PCI bridge: Intel Corporation 82801H (ICH8 Family) PCI Express Port 6 (rev 02) 00:1d.0 USB controller: Intel Corporation 82801H (ICH8 Family) USB UHCI Controller #1 (rev 02) 00:1d.1 USB controller: Intel Corporation 82801H (ICH8 Family) USB UHCI Controller #2 (rev 02) 00:1d.2 USB controller: Intel Corporation 82801H (ICH8 Family) USB UHCI Controller #3 (rev 02) 00:1d.7 USB controller: Intel Corporation 82801H (ICH8 Family) USB2 EHCI Controller #1 (rev 02) 00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev f2) 00:1f.0 ISA bridge: Intel Corporation 82801HB/HR (ICH8/R) LPC Interface Controller (rev 02) 00:1f.2 IDE interface: Intel Corporation 82801H (ICH8 Family) 4 port SATA Controller [IDE mode] (rev 02) 00:1f.3 SMBus: Intel Corporation 82801H (ICH8 Family) SMBus Controller (rev 02) 00:1f.5 IDE interface: Intel Corporation 82801HR/HO/HH (ICH8R/DO/DH) 2 port SATA Controller [IDE mode] (rev 02)
что касается сравнения, то в принципе тут проц от интела скорей всего намного мощнее оказался чем от амд:
Есть ноут на Athlon 300U Установлены Ubuntu 20.10, Firefox 82
В about:config включил media.ffmpeg.vaapi.enabled и layers.acceleration.force-enabled
При проигрывании видео 1080p лис жрёт 60+% проца согласно htop
Рядом ноут на оффтопике, проц там пошустрее (i7-10750H), но то же видео грузит проц всего на 3%.
А когда я вот эту видеокарту брал, амдшный графический проц был наоборот помощнее того же от нвидии, но там было двухсотое или трехсотое поколение нвидия 200 или 300 серия простеньких таких десктопных. Ну у i7 по любому будет площадь кристалла и ядер с конвеерами побольше чем у А300 я думаю. +Ко всему А300 это как урезанный АПУ наверное ;)…а i7 таки там так не задумывался.
Источник