3
March
2023
Dealing with DVD discs in Linux, FFMPEG program
18:52

Dealing with DVD discs in Linux, FFMPEG program

3 March 2023 18:52

КолLegs from time to time bring DVD discs with a request to save the film from the disk to the PC and convert it to the MPEG4 file. I tried to understand this problem and tell my experience with DVD discs.

Introduction

This article is written for yourself - to summarize the experience with DVD video in Linux for applications, such as:

  • Capture video from the finished DVD
  • Video and sound extraction
  • Cutting fragments
  • translation of video and sound to other formats
  • Association of several fragments into one file
  • Record on another disk.
    Section 10 shows the commands for working with DVD.
    The issue of the author’s creation of DVD in programs for designing DVDs is also briefly considered.

History of DVD-video

Initially, CD-R were created, which have a small reading speed (150 kbps for a speed of 1x, 1200 kbit/s for 8x), suitable for reproduction of sound. MPEG and MPEG2 video compression algorims used at that time (1996-2000) did not allow you to store a video quality video (D1 or PAL 720x576 for 50 fields per second). After the invention of DVD discs, the transmission speeds increased. Practically, the minimum reading speed of the DVD disk is 1,385,000 bytes per second (1.352 MB/s), and at the "24th" speed- 33240000 kbit/s or 32.4 MB/s for comparison, "studio" quality of video- 25 Mbps, and flows in the DVB-T2 multiplexes (MPEG4)- near 2.4-2.6 Mbps/s. DVD discs, on which the video is recorded, must correspond to the DVD video format that supports not only the storage of files, but also the “covers,“ chapters ”, the multi-channel sound 5+1 (6) channels and subtitles. The usual DVD disk has a volume of 4.7 GB, which is much higher than 700 MB at CD-R. High quality of the picture on household DVD players when using the MPEG2 and stereo and multi -channel sound in Dolby AC3 contributed to the rapid distribution of DVDs among consumers in the field of home entertainment industry. with a diameter of 1.46 GB As a large-capacity of BluRei for 4K video, the discs of the Blueeo spread slowly due to the high price.

The relevance of the DVD transfer problem to MPEG4 (AVC) / MKV files

The reason that users switch from DVD video to storage of old films in the form of MPEG4 files is durability. If we accept the initial date of use of DVD-video-2000, the average shelf life of discs is 20-60 years. In 2023, a certain part of the DVD-R discs may begin to read poorly. Also, recently, NFS (Network file storaGE) home storage facilities for home videos, films and photos. The advantage of NFS is the reservation and lack of risk of losing CD- or DVD disk as a result of mechanical damage (fall, scratches, etc.) Thus, the problem of transferring the DVD-video into other formats in 2023 is relevant.

1. Work diagram with DVD discs

Until 2002, a scheme for digitizing old video cassettes from the analog VHS video recorder worked.
VHS-Scheme

After 2002 and the present, after the transition to DVD, digitization of the old video is not done,
the processing cycle is completely in digital video using DVD and AVI / MP4 / MKV files on PC.

DVD_Scheme

All stages will be explained in the article later. A brief description of the scheme:

  1. In the left side-the source DVD-R or CD-R disc with video.

  2. To remove information from the DVD / CD discs, the Ripper program from the English word "rip" is used - to tear, tear, demolish. Instead of using DVD, you can simply open the disk in the conductor and copy its contents to the local PC.

  3. In the upper right side of the figure, a large square is the “transport” AVI file in the MPEG2 format containing video and sound of the same quality as the original DVD. This AVI file will be considered as the source material.

If the user asks to cut a fragment of the video, you can use the ff utilitympeg обработать файл и сохранить без изменений видео и звука часть видео в отдельный файл, с времени начала до времени конца. Видеомонтаж можно выполнить в программе - видеоредакторе openshot (есть в магазине приложений flatpak "FlaThub ”, and as a system package), and installing the video. In this article, a little attention will be paid to the installation issue.

  1. If the request consists in transcoding the video, the source file of AVI or the fragment cut out of the video will become the source material for the converter in the MPEG-4 Layer 2 (AVC). В центральной части рисунка - результат: файл на выходе контейнера - MP4 или MKV с видео сжатым в MPEG-4 (AVC) и звуком AC-3, для хранения в архиве на ПК. Такой файл MP4 или MKV имеет размер, как правило, значительно меньший чем размер DVD диска. Так как сжатие в MPEG4 AVC более эффективное при том же качестве можно использовать более низкую скорость потока (битрейт). К примеру, на DVD записано 90 минут видео - 4.7 Гбайт, из которых на видео 4.2 Гбайт и на звук 0.5 Гбайт, значит скорость потока видео будет 4.2*8*1024/(1.5*3600)=6.37 Мбит/с, а при сжатии в MP4 с битрейтом 2.4 Мбит/с занимаемый объём меньше в 2.4/6.37 *4.2 = 1.58 GB video + 0.5 GB sound = ~ 2.08 GB => i.e. The film will now occupy 56% less space .

  2. Recording directly MP4 on DVD as a “disk with data” is possible, but at the same time it will open ugly - not as a disk, but as a regular folder with a file, like a “flash drive”. To create a beautiful project of the new DVD disk or CD -R disk with the main menu - the DVD cover, the author's development program (DVD workshop) is used - such as DVDSTYLER , which was mentioned in the previous article. In it you can create the main menu displayed on the TV screen when loading DVD. The initial menu creates a overall impression of the disk, for example, “my vacation” with a background in the form of a summer landscape and may contain links or buttons that cause individual chapters of the movie. Also, some programs contain a built -in transcoder video - "converter", which will squeeze the video to the desired volume of the carrier.

  3. The program - the converter can not always be used, but only when it is necessary to recodit video between formats, for example, from MPEG2 to MPEG4 (AVC). The console utility FFMPEG can act as a converter, the examples of which will be considered in this article.

  4. DVD project burning for DVD-R or CD-R can often be executed from the program of the author's program. But in my opinion, it is better to use a record from the ISO image file in a specialized utility for ISO recording on DVD/CD, for example, xfburn, k3b или Brasero . The recording from the image is also used to release several copies of the disk.

Two processing methods - with transcoding and without:

  • Sveting If at some of the stages there is a change in the codec video or sound, there is a transcoding, for example, from MPEG2 to MPEG4. As a result, the quality worsens, especially on moving scenes and if the source material was recorded with a very high bitrate (studio level of 25-50 Mbps), and the result with low (0.8-1 Mbps). Depending on the quality of the initial video, the settings of the coder program, the number of passes (recommended 2) when reproducing the transcoding result - filemp4 потери не будут заметны глазу при битрейтах 2.5 - 3 Мбит/With. With strong compression of the video of the full resolution of the PAL 720x576i, artifacts may occur on the video - loss of clarity, "squares", "jelly", etc.
    * through processing (paththrough). В случае, если на всех этапах не используется преобразование (перекодирование) видео и аудио данных, не происходит потери качества. Такой способ называется "path-thrOUGH ", the data is not distorted, do not worsen or do not improve -" as is ". The MPEG2 file will have the quality of the source DVD. After that, the file can also be written on DVD without transcoding, in the MPEG2 format with the same sound as it was earlier.

2. Installing packages in Linux for playing DVD discs and individual AVI / MP4 files

2.1 Setting codecs video and sound

Libavcodec-extra - This is a metapack, which is responsible for installing the following codecs:

  • Libaom3 - Video Code library AV1
  • Libaribbb24-0-lib для декодирования ArIb StD-B24 (execution time files)
  • Libavutil56 - FFMPEG library with functions for simplifying programming - Files of execution time
  • Libcairo2 - CairO 2D Vector Graphic Library
  • Libcodec2-1.0 - Library of Codec2 execution time
  • Libdav1d5 - Fast and small decoder of the video stream AV1 (General Library)
  • Libgsm1 - General libraries for the GSM speech compressor
  • Liblzma5 - Compression library XZ -Format
  • Libmfx1 - Intel Media SDK - Общая библиотека
  • Libmp3lame0 - библиотека кодировки mP3
  • Libopencore -AmrNB0 - AMR of the Speech Codec - General Library
  • Libopencore -AmrWB0 - AMR -WB broadband speech codec - General library
  • Libopenjp2-7 - JPEG 2000 Image compression library/decompression
  • Libopus0 - Library for performing the execution time of OPUS CODEC
  • Librsvg2-2 - Render library for SVG files (execution time)
  • Libshine3 - MP3 encoding library with a fixed point - Forels of time execution
  • Libsnappy1v5 - библиотека быстрого сжатия/decompression
  • LibspeEx1 -Biblio Time of execution of the Speex code
  • LibswresamPle3 - FFMPEG library to revise sound, review, etc.
  • Libswresample3 - Кодек сжатия видео Theora
  • LibtwolamE0 - Audio MPEG Audio 2 Coding Library
  • LIBVa2 - API Video AcceleraTion (VA) for Linux - execution time
  • Libvo-amrwbenc0-библиотека энкодеров Amr-WB Visualon Amr-WB
  • Libvorbis0a - библиотека декодеров для общего кодека сжатия звука Vorbis
  • Libvorbisenc2 - библиотека Encoder для Vorbis GeneraL Audio Codec
  • LIBVPX7 - VP8 and VP9 Video Codec (General Library)
  • libwebp7 - compression with losses of digital photographic images (Webp)
  • libwebpmux3 - compression with losses of digital photographic images
  • Libx264-163 - X264 Video Coding Library
  • LIBX265-199 -H.265/Vide -Hevc flow (General Library)
  • Libxvidcore4 - Video codec with open source code MPEG -4 (library)
  • Libzvbi0 - Vertical interval -decoDER with interval (VBI) - execution time files
  • Zlib1g - compression library - environmental environment.

As you can see, the package libavcodec-extra через зависимости установит важнейшие кодеки видео MPEG-4, x264, h.265/HEVC and sound codes mp2, mp3.

1) in Ubuntu and Debian за кодеки отвечает пакет "libavcodec-extra".

sudo apt install libavcodec-extra

2) In Linux Mint, the DVD codecs are installed by the following command

sudo apt install mint-meta-codecs

If the PC C Linux Mint is not connected to the Internet, you need to download the codec package (apt download mint-meta-codecs), распаковать архив "mint-meta-codecs.tgz" на машине без Интернета и выполнить "sudo dpkG -I *. Deb "

For viewing commercial discs scored (if sessions are protected by CSS). It is not necessary to install the following packages if only household DVDs are used.
su -
apt install libdvdcss2 libdvdreaD8
apt install libdvd-pkG
dpkg-reconfigure libdvd-pkG

Additional package libavcodec-extra58 (не обязательный), содержит кодеки AMR для сотовых сетей, для DVD не требуется.

  • ARIB STD-B24 C Captions (Subtitle Decoder)
  • Opencore adaptive Multi-Rate (AMR) Narrow-Band (Encoder/Decoder)
  • Opencore adaptive Multi-Rate (AMR) Wide-Band (Decoder)
  • Android VisualOn Adaptive Multi-Rate (AMR) Wide-Band (Encoder)

    su -
    apt install libavcodec-extra58

2.2 installation of FFMPEG - Subsystems for working with video line video

The initial texts of the latest version of FFMPEG are on the site FFmpeg.orG intended for self -assembly (compilation).
For lazy users - you can install FFmpeg из репозитория. командой "apt instal ffmpeg "

SU -
apt install ffmPEG

DEBI featurean: поддерживается репозиторий www.deb-multimedia.org/pool с последними сборками ffmpeg для ОС Debian 10 Buster, 11 Bullseye, 12 Bookworm и нестабильной версии "Sid". О подключении репозитория рассказано на сайте https: // deb-multimedia.org/ - нужно добавить ключ в keyring, исправить файл apt - sources, после чего выполнить apt-get update и apt-get dist-upgrade
-> Pack ffmpeg and all depending will be updated to the latest versions.

Fedo featurera: ffmPEG is located in the repository for additional packages:https: //rpmfusion.org/ the installation of which is described in the section "configuration" для наиболее часто используемых версий Fedora и Red Hat.

Find out the version of FFmpeg можно командой ffmpeg -verSion

In Linux Mint 21.1 versions:
* ffmpeg verSion 4.4.2-0ubuntu0.22.04.1

  • lIbavutil 56. 70.100
  • Libavcodec 58.134.100
  • lIBavformat 58. 76.100
  • lIbavdevice 58. 13.100
  • Libavfilter 7.110.100
  • lIBSWSCALE 5. 9.100
  • lIBSWresamPle 3. 9.100
  • lIBPOSTPROC 55. 9.100

2.3 Installation of libraries for hardware acceleration video

Встроенная графика Intel:

ubuntu:

sudo apt install libva2 libva-x11-2

Debian:

SU -
apt install libva2 libva-x11-2

Fedora

sudo dnf install libva-intel-driver

Графика AMD (mesa) с поддержкой аппаратного декодирования видео:

ubuntu:

sudo apt install mesa-va-drivers mesa-vdpau-driverS.

Debian:

SU -
apt install mesa-va-drivers mesa-vdpau-driverS.

Fedora

sudo dnf swap mesa-va-drivers mesa-va-drivers-freeworLD

Sudo DNF SWap mesa-vdpau-drivers mesa-vdpau-drivers-freeworLD

Графика AMD - драйверы с поддержкой аппаратного ускорения:

Sudoadd-apt-repository ppa:oibaf/graphics-driverS.
sudo apt-get update
sudo apt install -y raDeon

Графика nVidia - драйверы с поддержкой аппаратного ускорения видео:

ubuntu:
In the "System" menu - "drivers" replace the driver with the source code Nouveau на "заказной" драйвер для видеокарты nVidia и перезагрузить ПК.
Linux Mint
In the menu "Parameters" - "driver manager" install a "custom" driver for the NVIDIA video card and restart the PC.
Fedora: source

sudo dnf install nvidia-vaapi-driver

2.4 Programs - "Video players" for playing DVD or files AVI, MP4, MKV

View DVD video in Linux is made in the MPV command line or graphic shell player - programs - "Cellulaid".

su -
apt install mPv Celluloid

For modern, more powerful PCs for playing DVD, VLC video player is more suitable.

SU -
apt install vlc vlc vlc-l10n vlc-plugin-base

3. Author's creation of DVD video in Linux

Free programs (FreewaTE):
Open DVD producer
TOVID - 2105г. можно задать фоновое изображение и звук для главного меню, запустить процесс создания DVD. Исходные тексты: https://github.com/tovid-suite/TOVID
*Varsha - программа для создания DVD с графическим интерфейсом (GUI), написана на Java, knows how to burn DVD discs.

  • DVDSTYLER - a program for creating DVD for Linux, Mac and Windows

    Installation of the DVDSTYLER program reviewed In a previous article. Since this program is cross-platform, working with the program in various operating systems does not differ.

As a material for videos, or chapters on the disk, I recommend high -quality video, for example, the following:

High quality source material
Video resolution - 720x576 Slice (InterlaCED, top field first).
Codec video - mpeg2 / h.262 / mpeg -2 part 2 с битрейтом 20 или 25 Мбит/With
Sound codec - PCM 16 bit stereo

Video and audio flows inside the container file can be seen in the Mediainfo program:

DVDSTYLE programr умеет как перекодировать материал в MPEG4 / AVC, так и записывать потоки видео и звука без обработки "path-through", добавляя лишь мультиплексирование видео x.264 и звука AAC (или MP2). Субтитры и телетекст DVDstyler не поддерживает.

Parameters of the resulting file with a video with sound for recording DVD: Parameter Meaning
Image
The format of the container AVI
Video format mpeg2 for "classic" DVD; For Chinese DVD players of BBK, etc. Suppose XVID or Divx3 / Divx4. Divx5
The attitude of the parties sh: in 4: 3 or 16: 9
Color space Yuv
Color subdiscretization 4: 2: 0 (main format)
4: 2: 2 (with increased requirements for color resolution)
color depth 8 bits
Type of scanning Separate (Interlaced)
The order of the fields The top field is the first (Top Field First)
compression With losses
Compression degree bits/(pixe *framE) from 0.8 to 2.2
width 720 pixels
Height 576 pixels
The speed of video stream (Bitrate video) from 2 to 25 Mbps - depending on the duration of the Content DVD. Often used VBR (flow 5.0-8.0 Mbps). For good quality when using CBR, it is recommended to choose a bitrate above 8 Mbit/s
25 Мбит/с CBR - студийное качество 720x576
4 Мбит/с - для разрешения 352x480
1.5-2 Мбит/C - for resolution QCIF 352x288
Basic colors, gear characteristics and matrix coefficients BT.709
Sound
The frequency of sampling audio signal 48 kHz
The number of channels (sound paths) 2 (for mp2 and PCM), 1 - 5.1 (for AC3)
Codec mp2 (mpeg2audio), Dolby AC-3 (AC3) или PCM (LPCM) 16 бит, 48 кГц - для "классических" DVD; для китайских проигрывателей допустим звук MP3 до 256k
audio speed (sound bitrate)

4. Work recording - xfburn

su -
apt install xfburn

Xfburn

5. Accepting information from the recorded DVD disk. Copying files from the Video_s folder

5.1 Method No. 1 - extracting files from the DVD -Video disk

DVD discs on the computer are recognized as a regular digital data carrier, with Video_ts folder.
It needs to be copied on a computer either manually or using the "DVDB utilityackUp ".
Small DVDB programackup для извлечения данных с DVD дисков для DebiaN and ubuntu.
Installation DVDBackup:

 apt install dvdbackUp

Using DVDBackup:

cd ~; mkdir dvd123
dvdbackup -M -i /dev/cdrom -o ~/dvd123

The main parameters dvdbackup:

-I - вывод информации о DVD.
-M --mirror зеркальное копирование DVD в папку на локальном диске
-i DEVICE - исходное устройство, где DEVICE может быть /dev/cdrom и т.п.
-o DIRECTORY - выходная папка для сохранения файлов с DVD. Если папка назначения не указана, будет использоваться текущий каталог.

5.2 Method No. 2 - Creating the image of the DVD -Video disk - file *. ISO

Removing information from DVE ("DVD Ripping") can be performed by regular tools - the DD program:

sudo dd if=/dev/cdrom of=disk.iso bs=1M

ISO images connection can be executed in PC file managermaNFM (http: // sourceforge.net/projects/pcmanfm)
In the context menu caused by the right mouse button: "open using" - "connection of disks images." ISO image will connect as a virtual DVD.

6. Description of files in the Video_ts folder

File Size Appointment Description
Video_ts.bup 12k Videomanager, v11 Резервная копия (BackUp) the Video_ts.ifo file in case of poor reading of the latter (due to scratches)
Video_ts.ifo 12k Videomanager, v11 File with information about DVD disk ( info ). The IFO file itself does not contain any video information. Instead, the iFo file refers to video data. It is used with VOB files, which stores actual audio and video data.
Video_ts.vob 76k Mpeg Sequence, V2, Program mUltiplex The beginning of content and usually contains menu and video trailers.
Video_01_0.bup 18k Video Title Set, V11 Reserve copy (backUp) the VTS_01_0.IFO file in case of poor reading of the latter (due to scratches)
Vts_01_0.ifo 18k Video Title Set, V11 Menu and subtitles. Binar file.
Vts_01_0.vob 234k Mpeg Sequence, V2, Program multiplex Файл видео, черная заставка 720x576i 25 кадров в секунду PAL, кодек видео MPEG2 / звука AAC. Часть 0
Vts_01_1.vob 500m Mpeg Sequence, V2, Program multiplex Основной файл видео, файл кино 720x576i 25 кадров в секунду PAL, кодек видео MPEG2 / звука AAC. Часть 1
Vts_01_2.vob 500m Mpeg Sequence, V2, Program multiplex Основной файл видео, файл кино 720x576i 25 кадров в секунду PAL, кодек видео MPEG2 / звука AAC. Часть 2
Vts_01_3.vob 500m Mpeg Sequence, V2, Program multiplex Основной файл видео, файл кино720x576i 25 кадров в секунду PAL, кодек видео MPEG2 / звука AAC. Часть 3

7. Reproduction of DVD-video files in various programs

MPV:

mpv VIDEO_TS.IFO

Cellulaid:

celluloid VIDEO_TS.IFO

VLC - unlike previous programs, the film does not start automatically, but is called on the screen of the disk menu (the menu is played)

vlc VIDEO_TS.IFO

8. Combining VOB files into one and converting the entire film into an AVI file without transcoding (quality: "the same quality")

cd ~/dvd123/VIDEO_TS
cat \*.VOB | pv | dd of=combined.vob
ffmpeg -i combined.vob -q:a 0 -q:v 0 -c copy -sn -y combined.avi

8.1 Convert into AVI of one specific VOB file from DVD in MPEG2 format:

ffmpeg -i VTS_01_1.VOB -q:a 0 -q:v 0 -c copy out-part1.avi

The transformation into AVI of one DVD VOB file into Divx, XVID, MPEG4, AVC format: copying method:

ffmpeg -i VTS_01_1.VOB -c:v libx264 -crf 0 -c copy out-x264.avi

Where is the key -crf заменяет ключи -q:v / -qscale:v которые игнорируются libx264.

CRF - COSTant Rate Factor (FFmpeg WikI coding H.264)
-crf 0 означает кодирование без потерь.

8.2 Transformation into AVI with simultaneous transcoding of the multi-channel sound Dolby AC-3 in mp3 stereo:

Note: on commercial DVDs and from video cameras with 3D-sound, the source sound can be in AC3 format (“Dolby AS-3”), then the sound is still necessary that the file is reproduced in most players.

Sound flow 160 kbps, quality -aq 2:

ffmpeg -i VTS_01_1.VOB -q:v 0 -vcodec copy -acodec libmp3lame -b:a 160k -aq 2 out-mp3.avi

In these examples of commands, if you need to convert the It film, replace the name of the file vts_01_1.vob on Combined.aVI.

9. Cut a fragment of video from ss seconds to tt seconds (quality: “The same quality”) using ffmpeg

For DVD files in MPEG2:

ffmpeg -i VTS_01_1.VOB -q:a 0 -q:v 0 -c copy -ss 0:28 -to 0:35 out-1_28-35.avi

For files in MPEG2 and DIVX/XVID/MPEG4/AVC:

ffmpeg -i VTS_01_1.VOB -crf 0 -c copy -ss 0:28 -to 0:35 out-1_28-35.avi

Where
-ss - start; 0:28 - time from the beginning of the video 0 minutes 28 seconds
-to - финиш ; 0:35 - время с начала видео 0 минут 35 секунд

10. Transcoding the source video of the AVI file using the FFMPEG tool

The general way to call FFMPEG:

ffmpeg -i исходный_файл параметры ... конечный файл

10.1 transcode the video in the MPEG4 / sound mp3 128k (кодек lamE)

File conversion 1.avi в out-mp4.aVI in MPEG2 format
КонTeiner of the resulting file - AVI, bitrate 1200 kbit/s CBR, MPEG4 format. Sound format - mp3 128k.

ffmpeg -i 1.avi -f avi -c:v mpeg4 -b:v 1200k -g 300 -bf 2 -c:a libmp3lame -b:a 128k out-mp4.avi

10.2 Sewth the video in the X264 / sound AAC 128K, in 2 passes

Stream 1200 kbit/s CBR - constant bit raTE, in two passes (the first pass “studies” the material, the second transcodes the video and adds sound in AAC format).

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -b:v 1200k -passlogfile 1_pass.log -f rawvideo -y /dev/null

ffmpeg -i 1.avi -pass 2 -vcodec libx264 -b:v 1200k -c:a aac -b:a 128k -passlogfile 1_pass.log out-avc.avi

10.3 Sewage video in the X264 / sound mp3 lame 128k с повышенным качеством, в 2 прохода

Stream 1200 kbit/s CBR - constant bit rate, кодек видео x264, звук VBR aq=2 (около 190 кБит/C, stereo).

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -b:v 1200k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -i 1.avi -pass 2 -vcodec libx264 -b:v 1200k -acodec libmp3lame --aq 2 -passlogfile 1_pass.log out-avc.avi

Video with quality 23 (VBR) -crf 23 для потока около 2Мбит/With:

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -crf 23 -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vcodec libx264 -crf 23 -acodec libmp3lame -b:a 160k -aq 2 -passlogfile 1_pass.log out-avc-crf23.avi

10.4 Svicing video in the X264 format; Copying sound without processing

Stream 1200 kbit/s CBR.

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -b:v 1200k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vcodec libx264 -b:v 1200k -c:a copy -q:a 0 -passlogfile 1_pass.log out-avc-acopy.avi

10.4 Surely video in the X264 format (MKV container); Copying sound (without processing)

Video stream 1200 kbit/s CBR:

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -b:v 1200k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vcodec libx264 -b:v 1200k -c:a copy -q:a 0 -passlogfile 1_pass.log out-avc.mkv

10.5 transcoding video file Format X264 (MP4 container); Copying sound (without processing)

Stream 1200k

ffmpeg -i 1.avi -pass 1 -vcodec libx264 -b:v 1200k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vcodec libx264 -b:v 1200k -c:a copy -q:a 0 -passlogfile 1_pass.log out-avc.mp4

10.6 transcoding video with a change in the resolution of SXV to 360x288, to the X264 format file (MP4 container); Sound mp3 lamE.

Stream 1200k

ffmpeg -i 1.avi -pass 1 -vf scale=360:288,setsar=1:1 -vcodec libx264 -b:v 700k -passlogfile 1_pass.log -f rawvideo -y /dev/Null FFmpeg -y -i 1.avi -pass 2 -vf scale=360:288,setsar=1:1 -vcodec libx264 -b:v 700k -acodec libmp3lame -b:a 160k -aq 2 -passlogfile 1_pass.log out-avc.mP4

10.7 Spending of a video with a change in the resolution of SXV to 360x756, while maintaining the attitude of the parties 4x3, to the file of the X264 format (MP4 container); Sound mp3 lamE.

ffmpeg -i 1.avi -pass 1 -vf scale=360:576,setsar=2/1 -vcodec libx264 -b:v 700k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vf scale=360:576,setsar=2/1 -vcodec libx264 -b:v 700k -acodec libmp3lame -b:a 160k -aq 2 -passlogfile 1_pass.log out_avc360x576.avi

10.8 Svicing a video with a change in the resolution of SXV to 720x288, while maintaining the attitude of the parties 4x3, to the X264 format file (MP4 container); Sound mp3 lamE.

ffmpeg -i 1.avi -pass 1 -vf scale=720:288,setsar=1/2 -vcodec libx264 -b:v 700k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vf scale=720:288,setsar=1/2 -vcodec libx264 -b:v 700k -acodec libmp3lame -b:a 160k -aq 2 -passlogfile 1_pass.log out_avc720x288.avi

10.9 transcoding video with a change in the resolution of SXV to 360x288, to the HEVC X265 format file (MKV container); Sound mp3 lamE.

ffmpeg -i 1.avi -pass 1 -vf scale=360:288,setsar=1/1 -vcodec libx265 -b:v 500k -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -y -i 1.avi -pass 2 -vf scale=360:288,setsar=1/1 -vcodec libx265 -b:v 500k -acodec libmp3lame -b:a 160k -aq 2 -passlogfile 1_pass.log out_x265.mkv

10.10 Svicing a file for Web (neat installation of flags - x264 profile High, LEVEL 3.1), format 4: 3; Sound mp3

Video format 4: 3:

ffmpeg -i 1.avi -t 10 -vf scale=360:288,setsar=1/1 -vcodec libx264 -b:v 400k -level 21 -refs 2 -pix_fmt yuv420p -profile:v high -level 3.1 -color_primaries 1 -color_trc 1 -colorspace 1 -movflags +faststart -af "pan=mono|c0=c1" -acodec libmp3lame -b:a 60k -dn web.mp4

Video format 16: 9 -
Parameter "Aspect": -Aspect 16: 9 with any input resolution.

ffmpeg -i 1.avi -t 10 -vf scale=640:360,setsar=1/1 -vcodec libx264 -level 21 -refs 2 -pix_fmt yuv420p -profile:v high -level 3.1 -color_primaries 1 -color_trc 1 -colorspace 1 -movflags +faststart -af "pan=mono|c0=c1" -acodec libmp3lame -b:v 500k -b:a 48k -dn web2.mp4

ffmpeg -i 1.avi -t 10 -vf scale=360:288,setsar=1/1 -vcodec libx264 -level 21 -refs 2 -pix_fmt yuv420p -profile:v high -level 3.1 -color_primaries 1 -color_trc 1 -colorspace 1 -movflags +faststart -af "pan=mono|c0=c1" -acodec libmp3lame -b:v 500k -b:a 48k -dn web2.mp4

-DN means not copying the data flow (Data - no).

Sound:

For a mono sound, add an audio filter -af "pan=mono|c0=c1". Для отключения звука - параметр -an (означает audio - no).

Instead of maximum speed -b:a 112k можно использовать параметр среднего качества
-aq 6 - приличное качество, битрейт 100-130k;
-aq 5 -satisfactory quality, bitrate 120-150;
-aq 4 - по умолчанию 140-185k;
-aq 2 очень хорошее качество 170-210k.
At -aq 1 размер файла в 1.5 раза выше, чем при -aQ 6, which is not justified for coding, for example, speech.

10.11 Coding with a variable bitrate, VBR speed from 1 Mbps to 2 Mbps (in complex areas), sound is also VBR with quality 8 (about 56 kbps)

ffmpeg -i 1.avi -c:v libx264 -b:v 1M -maxrate 2M -bufsize 2M -pass 1 -f mp4 -passlogfile 1_pass.log -f rawvideo -y /dev/null
ffmpeg -i 1.avi -c:v libx264 -b:v 1M -maxrate 2M -bufsize 2M -pass 2 -passlogfile 1_pass.log -acodec libmp3lame -af "pan=mono|c0=c1" -aq 8 vbr.mp4

10.12 Removing the sound path from the video - transformation into AAC (stereo) or WAV (mono)

ffmpeg -i 1.avi -vn -ac 2 -acodec aac sound.aac
ffmpeg -i 1.avi -vn -ac 1 - sound.wav

See also Here.

10.13 Improving the volume level of the sound track by +2DB

ffmpeg -i sound.wav -af "volume=+2dB" -y output.wav

10.14 Normalization, sound compression

ffmpeg -i sound.wav -af loudnorm=I=-10:LRA=1:tp=0 -ac 1 -y output.wav

10.15 Transformation WAV - MP2 (mon), flow rate 80kbit/S.

ffmpeg -i output.wav -acodec mp2 -ac 1 -b:a 80k -y final.mp2

10.16 Avi video Association with a new mp2 sound path (video is copied without transcoding)

ffmpeg -i 1.avi -i final.mp2 -c:v copy -map 0:v:0 -map 1:a:0 Final.avi

10.17 Coding with a set of parameters

Key -target pal-vcd задает следующий набор параметров:
-F VCD -muxrate 1411200 -muxpreload 0.44 -packEtsize 2324
-s 352x288 -r 25
-codec:v mpeg1video -g 15 -b:v 1150k -maxrate:v 1150v -minrate:v 1150k -bufsize:v 327680
-ar 44100 -aC 2
-codec:a mp2 -b:a 224k
Key -target pal-dvd задает следующий набор параметров:
-F DVD -muxrate 10080k -packEtsize 2048
-s 720x576 -pix_fmt yuv420p -r 25
-codec:v mpeg2video -g 15 -b:v 6000k -maxrate:v 9000k -minraTe: v 0 -Bufsize: v 1835008
-ar 48000
-codec:a ac3 -b:a 448k

Example: The source file has a resolution of 1280x720 (video from a smartphone),
the task is to record it on DVD:

ffmpeg -i 2.mp4 -target pal-dvd -aspect 16:9 out.avi

Result:
mediainfo_dvd_16_9

11 Recommended bitrates for stereo sound

  • ac3 >= 160k (для многоканального звука 5.1)
  • aac >= 128k (низкое качество - речь -b:a 128k )
  • mp3 >= 128k (для музыки рекомендуется -b:a 192k -aQ 2)

Recalculation of the bitrate for the desired number of channels:

*Битрейт = (битрейт для стерео) (число каналов / 2)**

For mono:

  • ac3 >= 80k
  • aac >= 64k (низкое качество - речь -b:a 64k )
  • mp3 >= 64k (для музыки рекомендуется -b:a 96k -aQ 2)

12. Standard video resolutions and their recommended bitrates

Technology Resolution P / I Frequency of personnel / fields, Hz Name Codec Bitrate (web, archive), Mbit/s Bitrate (good quality), Mbit/s
Analog 352x240p, 4: 3 Pal P 25/25 CIF, Pal DVD - VHS X.264 0.6 1.2
Analog 352x240p, 4: 3 NTSC P 29.97/29.97 CIF, NTSC DVD@23.976FPS X.264 0.6 1.2
Analog 352x288p, 4: 3 Pal P 25/25 Full CIF, FCIF X.264 0.75 1.5
Analog 704x480i, 4: 3 Pal I 25/50 D1, Pal X.264 0.8 2
Analog 720x480i, 4: 3 NTSC I 30/60 NTSC-D1 X.264 0.9 2.2
Analog 720x288p, 4: 3 25/25 P 2cif, Half-D1 X.264 0.8 1.8
analog / digital 720x576i, 4: 3 or 16: 9 I 25/50 Full-D1, Pal broadcaST, DVD , SD X.264 1.3 2.5
Digital 544x576i, 16: 9 25/50 I Broadcast with reduced quality X.264 1.2 2.2
Digital 480x576i, 16: 9 25/50 I Broadcast with reduced quality X.264 1 2
Digital 352x576i, 16: 9 25/50 I Broadcast with reduced quality X.264 0.8 1.8
Digital 352x288p, 16: 9 25/25 I Broadcast with reduced quality X.264 0.6 1.3
Analog 768x576i, 16: 9 25/50 I Pal-DV X.264 1.3 2.5
Digital 1280x720p, 16: 9 P 25/25 720p, HD X.264 2 4
Digital / analog (video surveillance systems: AHD, MHD) 1920x1080 I 25/50 Full-HD or 2K) X.264 3 5
Digital 1920x1080p 30/30 Full HD 1080p 30fps or 2K-30FPS P 30 X.264 4 7
Digital 1920x1080p 60/60 Full HD 60FPS or 2K-60FPS P 60 X.264 6 10
Digital 2560x1440p 25, 3k P 25 X.265 12 22
Digital 3840x2160p 30, 60, 120 4K or UHD P 30, 60 or 120 X.265 12 22

Application. The ratio of video formats by the structure of the frame

D1 = Pal BroadcaST

D1 = 4CIF
CIF = 1/4 D1

HalfD1=1/2 d1
2cif = 1/2 d1
2cif = Halfd1

Appendix 2. The ratio of the areas of video formats (or the number of image elements - pixels)

FullHD = 2K
FullHD = 5 * Pal BroadcaST
FullHD = 2.25 HD
Fullhd = 0.75 3k
FullHD = 1/2 UHD
Fullhd = 1/4 8k


Source:https: // trac.ffmpeg.org/wikI