Цифровой садик - приветственная

Цифровой садик - приветственная | Полный список всего, что тут есть | RSS | Подписаться через follow.it

13.07.2022

ffmpeg

Остальное - библиотеки, меня не касается пока. )

FFmpeg and H.264 Encoding Guide

The goal of this guide is to inform new users how to create a high-quality H.264 video using the encoder x264.

There are two rate control modes that are usually suggested for general use: Constant Rate Factor (CRF) or Two-Pass ABR. The rate control is a method that will decide how many bits will be used for each frame. This will determine the file size and also how quality is distributed.

Constant Rate Factor (CRF)

This method allows the encoder to attempt to achieve a certain output quality for the whole file when output file size is of less importance. This provides maximum compression efficiency with a single pass. Each frame gets the bitrate it needs to keep the requested quality level. The downside is that you can't tell it to get a specific filesize or not go over a specific size or bitrate.

1. Choose a CRF value

The range of the quantizer scale is 0-51: where 0 is lossless, 23 is default, and 51 is worst possible. A lower value is a higher quality and a subjectively sane range is 18-28. Consider 18 to be visually lossless or nearly so: it should look the same or nearly the same as the input but it isn't technically lossless.

The range is exponential, so increasing the CRF value +6 is roughly half the bitrate while -6 is roughly twice the bitrate. General usage is to choose the highest CRF value that still provides an acceptable quality. If the output looks good, then try a higher value and if it looks bad then choose a lower value.

Note: The CRF quantizer scale mentioned on this page only applies to 8-bit x264 (10-bit x264 quantizer scale is 0-63). You can see what you are using by referring to the ffmpeg console output during encoding (yuv420p or similar for 8-bit, and yuv420p10le or similar for 10-bit). 8-bit is more common among distributors.

2. Choose a preset

A preset is a collection of options that will provide a certain encoding speed to compression ratio. A slower preset will provide better compression (compression is quality per filesize). This means that, for example, if you target a certain file size or constant bit rate, you will achieve better quality with a slower preset. Similarly, for constant quality encoding, you will simply save bitrate by choosing a slower preset.

The general guideline is to use the slowest preset that you have patience for. Current presets in descending order of speed are: ultrafast,superfast, veryfast, faster, fast, medium, slow, slower, veryslow, placebo. The default preset is medium. Ignore placebo as it is not useful (see FAQ). You can see a list of current presets with -preset help (see example below), and what settings they apply with x264 –fullhelp.

You can optionally use -tune to change settings based upon the specifics of your input. Current tunings include: film, animation, grain, stillimage, psnr, ssim, fastdecode, zerolatency. For example, if your input is animation then use the animation tuning, or if you want to preserve grain then use the grain tuning. If you are unsure of what to use or your input does not match any of tunings then omit the -tune option. You can see a list of current tunings with -tune help, and what settings they apply with x264 –fullhelp.

Another optional setting is -profile:v which will limit the output to a specific H.264 profile. This can generally be omitted unless the target device only supports a certain profile (see Compatibility). Current profiles include: baseline, main, high, high10, high422, high444. Note that usage of -profile:v is incompatible with lossless encoding.

To list all possible internal preset and tunes:

ffmpeg -f lavfi -i nullsrc -c:v libx264 -preset help -f mp4 -

Two-Pass

This method is generally used if you are targeting a specific output file size and output quality from frame to frame is of less importance. This is best explained with an example. Your video is 10 minutes (600 seconds) long and an output of 200 MiB is desired. Since bitrate = file size / duration:

(200 MiB * 8192 [converts MiB to kBit]) / 600 seconds = ~2730 kBit/s total bitrate 2730 - 128 kBit/s (desired audio bitrate) = 2602 kBit/s video bitrate You can also forgo the bitrate calculation if you already know what final (average) bitrate you need.

Two-Pass Example

  ffmpeg -y -i input -c:v libx264 -preset medium -b:v 2600k -pass 1 -c:a aac -b:a 128k -f mp4 /dev/null && \
ffmpeg -i input -c:v libx264 -preset medium -b:v 2600k -pass 2 -c:a aac -b:a 128k output.mp4

As with CRF, choose the slowest preset you can tolerate.

In pass 1 specify a output format with -f that matches the output format in pass 2. Also in pass 1, specify the audio codec used in pass 2; in many cases -an in pass 1 will not work.

Lossless H.264

You can use -crf 0 to encode a lossless output. Two useful presets for this are ultrafast or veryslow since either a fast encoding speed or best compression are usually the most important factors.

Lossless Example (fastest encoding)

ffmpeg -i input -c:v libx264 -preset ultrafast -crf 0 output.mkv

Lossless Example (best compression)

ffmpeg -i input -c:v libx264 -preset veryslow -crf 0 output.mkv

Note that lossless output files will likely be huge, and most non-FFmpeg based players will not be able to decode lossless, so if compatibility or file size issues you should not use lossless. If you're looking for an output that is roughly "visually lossless" but not technically lossless use a -crf value of around 17 or 18 (you'll have to experiment to see which value is acceptable for you). It will likely be indistinguishable from the source and not result in a huge, possibly incompatible file like true lossless mode.

Overwriting default preset settings

You can overwrite default preset settings with the x264-params option, or by using the libx264 private options (see ffmpeg -h encoder=libx264). This is not recommended unless you know what you are doing. The presets were created by the x264 developers and tweaking values to get a better output is usually a waste of time.

Example:

ffmpeg -i input -c:v libx264 -preset slow -crf 22 -x264-params keyint=123:min-keyint=20 -c:a copy output.mkv

Additional Information & Tips

CBR (Constant Bit Rate)

There is no native CBR mode, but you can "simulate" a constant bit rate setting by tuning the parameters of ABR:

ffmpeg -i input.mp4 -c:v libx264 -x264-params "nal-hrd=cbr" -b:v 1M -minrate 1M -maxrate 1M -bufsize 2M output.ts

In the above example, -bufsize is the "rate control buffer" so it will enforce your requested "average" (1 MBit/s in this case) across each 2 MBit worth of video. So basically it is assumed that the receiver/end player will buffer that much data so it's ok to fluctuate within that much.

Of course, if it's all just empty/black frames then it will still serve less than that many bits/s but it will raise the quality level as much as it can.

Constained encoding (VBV / maximum bit rate)

You can also also use -crf or -b:v with a maximum bit rate by specifying both -maxrate and -bufsize:

ffmpeg -i input -c:v libx264 -crf 23 -maxrate 1M -bufsize 2M output.mp4

This will effectively "target" -crf 23, but if the output were to exceed 1 MBit/s, the encoder would increase the CRF to prevent bitrate spikes.

In another example, instead of using constant quality (CRF) as a target, the average bitrate is set. A two-pass approach is preferred here:

ffmpeg -i input -c:v libx264 -b:v 1M -maxrate 1M -bufsize 2M -pass 1 -f mp4 /dev/null
ffmpeg -i input -c:v libx264 -b:v 1M -maxrate 1M -bufsize 2M -pass 2 output.mp4
Low Latency

libx264 offers a -tune zerolatency option. https://trac.ffmpeg.org/wiki/StreamingGuide

Информация о файле

ffprobe имя-файла - по умолчанию выдаёт примерно ту же информацию, что ffmpeg -i имя-файла, позволяет всячески уточнять, что именно интересует.

Захват

С веб-камеры

ffmpeg -f video4linux2 -i /dev/video0 test.mpg

С рабочего стола:

Use the x11grab device:

ffmpeg -video_size 1024x768 -framerate 25 -f x11grab -i :0.0+100,200 output.mp4

This will grab the image from desktop, starting with the upper-left corner at (x=100, y=200) with the width and height of 1024x768.

If you need audio too you can use ALSA (see Capture/ALSA for more info):

ffmpeg -video_size 1024x768 -framerate 25 -f x11grab -i :0.0+100,200 -f alsa -ac 2 -i hw:0 output.mkv

Or the pulse input device:

ffmpeg -video_size 1024x768 -framerate 25 -f x11grab -i :0.0+100,200 -f pulse -ac 2 -i default output.mkv

If you want a perfect recording of your desktop, x264 can help. Use lossless encoding, e.g.:

ffmpeg -video_size 1920x1080 -framerate 30 -f x11grab -i :0.0 -c:v libx264 -qp 0 -preset ultrafast capture.mkv

-qp 0 tells x264 to encode in lossless mode, -preset ultrafast advises it to do so fast.

The encoder should be fast enough on most modern hardware to record without any framedrop, and even leave enough CPU headroom for other applications.

If you're going to archive the recording or are concerned about file size, re-encode it losslessly again but with a slower preset. Note that since the initial recording was lossless, and the re-encode is lossless too, no quality loss is introduced in this process in any way.

ffmpeg -i capture.mkv -c:v libx264 -qp 0 -preset veryslow capture_smaller.mkv

Видео в последовательность картинок

Работает, но надо разбираться с настройками.

ffmpeg -i 1\ Светлячки.avi -f image2 1-%04d.png

Отдельный кадр -

ffmpeg -ss 00:00:02 -i "file.flv" -f image2 -vframes 1 "file_out.jpg"

-ss [start] -t [duration]

Последовательность картинок в видео

ffmpeg -i frame%04d.png -c:v ffv1 -qscale:v 0 test.avi
ffmpeg -f image2 -i image%d.jpg -vcodec mpeg4 -b 800k video.avi
ffmpeg -f image2 -pattern_type glob -framerate 25 -i 'images-*.png' -c:v mpeg4 -tag xvid  -q:v 1  video.avi

The external encoding library libxvid:

ffmpeg -i input.avi -c:v libxvid output.avi

…and the native encoder mpeg4:

ffmpeg -i input.avi -c:v mpeg4 -vtag xvid output.avi

You can select a video quality level with -qscale:v n (or the alias -q:v n), where n is a number from 1-31, with 1 being highest quality/largest filesize and 31 being the lowest quality/smallest filesize. This is a variable bit rate mode, roughly analogous to using -qp (constant QP - quantization parameter) with x264. Most of the time this should be the preferred method.

You can select an audio quality level with -qscale:a (or the alias -q:a). The value changes depending on the audio encoder. Since this guide uses libmp3lame see the MP3 Encoding Guide (https://trac.ffmpeg.org/wiki/Encode/MP3) for examples and more information.

ffmpeg -i input.avi -c:v mpeg4 -vtag xvid -qscale:v 3 -c:a libmp3lame -qscale:a 4 output.avi

There is rarely a need to use -qscale:v 1. Note that if you choose it, libxvid will take much more space than the same video compressed with the native mpeg4 encoder.

ffmpeg -r a -i "image_%%03d.jpg" -t b -i "audio.mp3" -y -r c "output.mp4"
  • a — frame rate, количество изображений в секунду. Если это значение < 1, то нужно обязательно указывать -r c, чтобы выходное видео получилось корректным и воспринималось всеми стандартными плеерами.
  • b — продолжительность звучания аудио. В моем случае указывается продолжительность видео, чтобы аудио не вылезло за границы. Узнать продолжительность можно с помощью ffprobe, а в данном случае она равна n / a, где n — количество входных изображений.
  • c — frame rate результирующего видео.

https://habrahabr.ru/post/171213/#comment_5983539

Слайдшоу

ffmpeg -r 0.1 -y -i "image_%010d.png" output.mpg

слайдшоу, чтобы картинки сменяли друг друга через каждые n секунд - в данном случае 10. -r - framerate. 1 - кадр в секунду.

ffmpeg -r a -i "image_%%03d.jpg" -t b -i "audio.mp3" -y -r c "output.mp4"
  • a — frame rate, количество изображений в секунду. Если это значение < 1, то нужно обязательно указывать -r c, чтобы выходное видео получилось корректным и воспринималось всеми стандартными плеерами.
  • b — продолжительность звучания аудио. В моем случае указывается продолжительность видео, чтобы аудио не вылезло за границы. Узнать продолжительность можно с помощью ffprobe, а в данном случае она равна n / a, где n — количество входных изображений.
  • c — frame rate результирующего видео. frame rate результирующего видео обычно равен 30.

И если нужно сгенерировать таким способом видео из 3 картинок например, то входных картинок должно быть на самом деле 4, где первая и вторая будут повторяться (не знаю почему так, но именно так работает правильно)

Захват видео с экрана

ffmpeg -f x11grab -s cif -r 25 -i :0.0+10,20 /tmp/out.mpg

здесь -s cif — размер, 0.0 — экран, 10,20 — это смещение относительно верхнего левого угла экрана

Изменение размера

ffmpeg -i 170420.mp4 -s 720x480 -crf 28 -y -preset superfast  170420-lightened.mp4

Перекодировка в заданном размере, с невысоким качеством, быстро.

Обрезка

ffmpeg -i in.mp4 -ss [start] -t [duration] -c copy out.mp4
  • in.mp4 – исходное видео
  • out.mp4 – обрезанное видео
  • \[start\] – начало видеофрагмента (в секундах или в формате hh:mm:ss),
  • \[duration\] – длительность видеофрагмента (в секундах или в формате hh:mm:ss)

Например, чтобы обрезать видео и оставить в нем только первые пять минут достаточно ввести следующую команду:

ffmpeg -i in.mp4 -ss 0 -t 300 -c copy out.mp4

или

ffmpeg -i in.mp4 -ss 0 -t 00:05:00 -c copy out.mp4

Склейка

ffmpeg -i 'concat:1.avi|2.avi|3.avi|4.avi|5.avi|6.avi' -i source/KiyoshiYoshida.mp3 -c copy all.avi

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

ffmpeg -f concat -safe 0 -i list.txt -c copy output

The -safe 0 above is not required if the paths are relative.

If your shell supports process substitution (like Bash and Zsh), you can avoid explicitly creating a list file and do the whole thing in a single line. This would be impossible with the concat protocol (see below). Make sure to generate absolute paths here, since ffmpeg will resolve paths relative to the list file your shell may create in a directory such as "proc/self/fd".

ffmpeg -f concat -safe 0 -i <(for f in ./*.wav; do echo "file '$PWD/$f'"; done) -c copy output.wav
ffmpeg -f concat -safe 0 -i <(printf "file '$PWD/%s'\n" ./*.wav) -c copy output.wav
ffmpeg -f concat -safe 0 -i <(find . -name '*.wav' -printf "file '$PWD/%p'\n") -c copy output.wav

You can also loop a video. This example will loop input.mkv 10 times:

for i in {1..10}; do printf "file '%s'\n" input.mkv >> mylist.txt; done
ffmpeg -f concat -i mylist.txt -c copy output.mkv

If you have MP4 files, these could be losslessly concatenated by first transcoding them to mpeg transport streams. With h.264 video and AAC audio, the following can be used:

ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate1.ts
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts intermediate2.ts
ffmpeg -i "concat:intermediate1.ts|intermediate2.ts" -c copy -bsf:a aac_adtstoasc output.mp4

If you're using a system that supports named pipes, you can use those to avoid creating intermediate files - this sends stderr (which ffmpeg sends all the written data to) to /dev/null, to avoid cluttering up the command-line:

mkfifo temp1 temp2
ffmpeg -i input1.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp1 2> /dev/null & \
ffmpeg -i input2.mp4 -c copy -bsf:v h264_mp4toannexb -f mpegts temp2 2> /dev/null & \
ffmpeg -f mpegts -i "concat:temp1|temp2" -c copy -bsf:a aac_adtstoasc output.mp4

All MPEG codecs (H.264, MPEG4/divx/xvid, MPEG2; MP2, MP3, AAC) are supported in the mpegts container format, though the commands above would require some alteration (the -bsf bitstream filters will have to be changed).

Склейка при разных кодеках

ffmpeg -i input1.mp4 -i input2.webm \
-filter_complex "[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]" <encoding options> output.mkv

On the \verb|-filter_complex| line, the following:

[0:v:0] [0:a:0] [1:v:0] [1:a:0]

tells ffmpeg what streams to send to the concat filter; in this case, video stream 0 [0:v:0] and audio stream 0 [0:a:0] from input 0 (input1.mp4 in this example), and video stream 0 [1:v:0] and audio stream 0 [1:v:0] from input 1 (input2.webm).

concat=n=2:v=1:a=1 [v] [a]'

This is the concat filter itself. n=2 is telling the filter that there are two input files; v=1 is telling it that there will be one video stream; a=1 is telling it that there will be one audio stream. [v] and [a] are names for the output streams to allow the rest of the ffmpeg line to use the output of the concat filter.

Note that the single quotes around the whole filter section are required.

-map '[v]' -map '[a]'

This tells ffmpeg to use the results of the concat filter rather than the streams directly from the input files.

Note that filters are incompatible with stream copying; you can't use -c copy with this method.

Извлечь звуковую дорожку

ffmpeg -i source_video.avi -vn -ar 44100 -ac 2 -ab 192 -f mp3 sound.mp3

Пояснения:

  • Источник: source_video.avi
  • Битрейт аудио: 192kb/s
  • Выходной формат: mp3
  • Полученный аудиофайл: sound.mp3

Конкретную.

Say, we have a video file and we need to extract specific audio track from it. First, let's see which audio tracks we have in this file. Run the following command:

ffmpeg -i <videofile>

Look at the output and find strings starting with "Stream \#":

Stream #0:0: Video: mpeg4 (Advanced Simple Profile) (XVID / 0x44495658), yuv420p, 720x304 [SAR 1:1 DAR 45:19], 23.98 tbr, 23.98 tbn, 23.98 tbc
Stream #0:1: Audio: ac3 ([0] [0][0] / 0x2000), 48000 Hz, 5.1(side), s16, 448 kb/s

Let's extract audio track (stream 0:1):

ffmpeg -i <videofile> -map 0:1 -vn -acodec copy output.ac3

Приклеить звуковую дорожку

ffmpeg -i son.wav -i video_origine.avi video_finale.mpg

Несколько звуковых дорожек

У нас есть видеофайл с одной аудиодорожкой, к которому мы хотим подклеить ещё две.

ffmpeg -i <sourceVideoFile> -i <sourceAudioFile1> -i <sourceAudioFile2> -map 0:0 -map 0:1 -map 1:0 -map 2:0 -c:v copy -c:a copy <outputVideoFile>
  • скармливаем три файла-источника, каждый через \texttt{-i}
  • теперь 4 -map параметра. Каждый добавляет поток(дорожку) в результат. После -map мы пишем, откуда берём дорожку. Первое число - номер файла-источника (в порядке добавления через -i раньше), второе - номер дорожки внутри этого файла (нумеруются, начиная с нуля). В нашем случае:
    • map 0:0: copy stream 0 from first file (this is video stream) to stream 0 of output file
    • map 0:1: copy stream 1 from first file (this is audio stream) to stream 1 of output file
    • map 1:0: copy stream 0 from second file to stream 2 of output file
    • map 2:0: copy stream 0 from third file to stream 3 of output file
  • c:v copy means «Copy all video streams without re-encoding»
  • c:a copy means «Copy all audio streams without re-encoding»

Замедлить-ускорить

В этих примерах с аудиодорожкой ничего не происходит, поэтому лучше её вообще убрать через -an.

Замедлить:

ffmpeg -i inputfile -vf  "setpts=4*PTS" outputfile

Ускорить:

ffmpeg -i inputfile -vf  "setpts=0.5*PTS" outputfile

The filter works by changing the presentation timestamp (PTS) of each video frame. For example, if there are two succesive frames shown at timestamps 1 and 2, and you want to speed up the video, those timestamps need to become 0.5 and 1, respectively. Thus, we have to multiply them by 0.5.

Note that this method will drop frames to achieve the desired speed. You can avoid dropped frames by specifying a higher output frame rate than the input. For example, to go from an input of 4 FPS to one that is sped up to 4x that (16 FPS):

ffmpeg -i input.mkv -r 16 -filter:v "setpts=0.25*PTS" output.mkv

Speeding up/slowing down audio

You can speed up or slow down audio with the ​atempo audio filter. To double the speed of audio:

ffmpeg -i input.mkv -filter:a "atempo=2.0" -vn output.mkv

The atempo filter is limited to using values between 0.5 and 2.0 (so it can slow it down to no less than half the original speed, and speed up to no more than double the input). If you need to, you can get around this limitation by stringing multiple atempo filters together. The following with quadruple the audio speed:

ffmpeg -i input.mkv -filter:a "atempo=2.0,atempo=2.0" -vn output.mkv

Using a complex filtergraph, you can speed up video and audio at the same time:

ffmpeg -i input.mkv -filter_complex "[0:v]setpts=0.5*PTS[v];[0:a]atempo=2.0[a]" -map "[v]" -map "[a]" output.mkv
ffmpeg -i VID_20190708_215304.3gp -filter_complex "[0:v]setpts=2*PTS[v];[0:a]atempo=0.5[a]" -map "[v]" -map "[a]" sslowed.mp4

Ещё вариант

Изменить частоту кадров в видеопотоке позволяет программа yuvfps из пакета mjpegtools. Как и большинство утилит пакета она принимает и отдаёт видеопоток в формате YUV4MPEG. И ffmpeg, и mencoder тоже умеют работать с YUV4MPEG (и умеют читать и писать всякие другие форматы). Я приведу пример использования ffmpeg.

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

ffmpeg -i normal.ogg
FFmpeg version SVN-r13582, Copyright (c) 2000-2008 Fabrice Bellard, et al.
...
Input #0, ogg, from 'normal.ogg':
  Duration: 00:00:10.49, start: 0.000000, bitrate: 150 kb/s
    Stream #0.0: Video: theora, yuv420p, 320x240 [PAR 1:1 DAR 4:3], 30.00 tb(r)
Must supply at least one output file

В данном случае исходный файл — 30 кадров в секунду. Затем нужно решить, во сколько раз уменьшить число кадров (исходя из желаемой длительности ролика). Потом берём исходный файл (normal.ogg в примере) и преобразовываем его в YUV4MPEG-поток (первый вызов ffmpeg), после нужно дважды вызвать yuvfps, первый раз, чтобы изменить число кадров в потоке (yuvfps -s 5:2 -r 1:1 сокращает исходные 2.5 кадра до одного), второй раз, чтобы перезаписать заголовок потока, указав скорость воспроизведения (yuvfps -r 30:1 -c устанавливает скорость 30 кадров в секунду). В конце опять вызываем ffmpeg и кодируем в нужный формат (я сохранил в формате Ogg/Theora, чтобы можно было вставлять в веб-странички тэгом <video>). Всё вместе:

ffmpeg -i normal.ogg -f yuv4mpegpipe - | yuvfps -s 5:2 -r 1:1 | yuvfps -r 30:1 -c | ffmpeg -f yuv4mpegpipe -i - -y fast.ogg

-sameq - не поддерживается.

Аналогично можно увеличить число кадров. Дополнительные кадры интерполируются:

ffmpeg -i normal.ogg -f yuv4mpegpipe - | yuvfps -s 1:3 -r 1:1 | yuvfps -r 30:1 -c |  ffmpeg -f yuv4mpegpipe -i - -y slow.ogg

В этот раз видео замедляется в 3 раза: на каждую «треть» исходного кадра (-s 1:3) создаётся целый кадр (-r 1:1). Вообще, как легко заметить, в качестве частоты кадров для yuvfps можно указывать любые дроби в виде числитель:знаменатель.

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

Про перекодировку

Here is an example which should give you the highest quality video (I'm not speaking about the resulting file size). Note that this video might not be playable on all devices or players:

ffmpeg -i MyMovie.mkv -vf scale=-1:720 -c:v libx264 -crf 0 -preset veryslow -c:a copy MyMovie_720p.mkv

To get a "visually lossless" quality, you can use:

ffmpeg -i MyMovie.mkv -vf scale=-1:720 -c:v libx264 -crf 18 -preset veryslow -c:a copy MyMovie_720p.mkv

Now let's see what we have here:

The scale video filter is for resizing the video. You just set one size – which is the height in this example – and use -1 for the other dimension. ffmpeg will recalculate the correct value automatically while preserving the aspect ratio.

Quality controlled with the -crf option:

The range of the quantizer scale is 0-51: where 0 is lossless, 23 is default, and 51 is worst possible. A lower value is a higher quality and a subjectively sane range is 18-28. Consider 18 to be visually lossless or nearly so: it should look the same or nearly the same as the input but it isn't technically lossless.

The range is exponential, so increasing the CRF value +6 is roughly half the bitrate while -6 is roughly twice the bitrate. General usage is to choose the highest CRF value that still provides an acceptable quality. If the output looks good, then try a higher value and if it looks bad then choose a lower value. You can find more info in the x264 encoding guide.

You control the tradeoff between video encoding speed and compression efficiency with the -preset options. Those are ultrafast, superfast, veryfast, faster, fast, medium, slow, slower, veryslow. Default is medium. The veryslow option offers the best compression efficiency (resulting in a smaller file size for the same quality) but it is very slow – as the name says.

The audio will be stream copied directly from the input file to the output file without any changes.

Изменить aspect ratio и более ничего

ffmpeg -i input.avi -vcodec copy -aspect 16:9 -acodec copy output.avi 

Наложить картинку

ffmpeg -i 1.mp4 -vf "movie=logo.png [logo]; [in][logo] overlay=16:16[out]" -crf 18 2.mkv

ffmpeg -i faded.mp4 -vf "movie=logo.png [logo]; [in][logo] overlay=900:800[out]" -crf 18 withwatermark.mkv

Тут необходимо перекодирование, потому надо задать параметры кодировки, что и выполняет опция -crf 18. Ватермарка лежит в том же каталоге под именем logo.png. Параметр 16:16 - координаты позиционирования верхнего левого угла ватермарки.

Параметр CRF является некоторым уровнем качества и принимает значения от 0 до 51, где 0 - наилучшее качество; 51 - наихудшее качество. Если выбрать больше 51, например 54 или 9000 - будет браться всё равно 51. В документации рекомендуется значение 18, выдающее качество "практически равное исходному файлу".

Наложить видео на видео

You can use the scale and overlay video filters. This example will make "foreground.mp4" half sized and place it in the top left of the background. The audio will be stream copied from "background.mp4".

If you want the output to terminate when the shortest input terminates:

ffmpeg -i background.mp4 -i foreground.mp4 -filter_complex \
"[0:v]setpts=PTS-STARTPTS[bg]; \
 [1:v]scale=iw/2:-1,setpts=PTS-STARTPTS[fg]; \
 [bg][fg]overlay=W-w-10:0:shortest=1[out]" \
-map "[out]" -map 0:a -codec:v libx264 -crf 23 -preset medium -codec:a copy -movflags +faststart output.mp4

If the foreground is shorter than the background but you want the background video to continue:

ffmpeg -i background.mp4 -i foreground.mp4 -filter_complex \
"[0:v]setpts=PTS-STARTPTS[bg]; \
 [1:v]scale=iw/2:-1,setpts=PTS-STARTPTS[fg]; \
 [bg][fg]overlay=W-w-10:0:eof_action=pass[out]" \
-map "[out]" -map 0:a -codec:v libx264 -crf 23 -preset medium -codec:a copy -movflags +faststart output.mp4

Be aware that frames are taken from each input video in timestamp order, hence, if their initial timestamps differ, it is a good idea to pass the two inputs through a setpts=PTS-STARTPTS filter to have them begin in the same zero timestamp as shown in these examples.

Обрезка кадра

ffmpeg -i 1.mp4 -filter:v "crop=1066:768:300:0" -crf 18 cut.mp4

Первая пара (1066:768) задаёт новый размер кадра, а вторая (300:0) - координаты его левого верхнего угла относительно исходного.

Для этого необходимо перекодирование, потому надо задать параметры кодировки, что и выполняет опция -crf 18.

Непонятный реалтайм

наложение меняющегося лого на трансляцию.

ffmpeg -rtsp_transport tcp -i "rtsp://admin:12345@xx.xxx.xx.x/h264" -loop 1 -i "/home/cam/iptv_broadcast/logo.png" -filter_complex "[0:v][1:v] overlay=25:25, drawtext=textfile=/path/to/temperature:reload=1" -vcodec libx264 -b:v 3000k  -f mpegts "udp://@xxx.xxx.x.xxx:xxxx"

Неподвижное изображение + аудио, для ютюба

ffmpeg -loop_input -shortest -f image2 -i ''image.png'' -f wav -i ''audio.wav'' ''output.avi''

Субтитры

ffmpeg -i input.avi -vf subtitles=subtitles.srt output.avi

Можно использовать и ass (http://ffmpeg.org/ffmpeg-filters.html#ass) с фильтром ass вместо subtitles, и дорожку с субтитрами из файла с видео.

У меня выдавало непонятную ошибку, пока я не догадалась проверить кодировку субтитров. По умолчанию должна быть utf-8. Можно указать: subtitles=sub.srt:charenc=encoding, мне было проще сконвертировать.

Может иметь смысл указать -crf 18, чтоб качество файла не сильно падало.

Фильтры

ffmpeg -filters - дабы узнать, какие есть.

вращение

ffmpeg -i VID_20180228_160756_000024.3gp -vf "rotate=270" -crf 15 VID_20180228_160756_000024_rotated.mp4

Вполне рабочий вариант поворота.

ffmpeg -i VID_20181207_202750.3gp -vf "transpose=dir=cclock:passthrough=landscape" -crf 15 VID_20181207_202750_a.mp4

Другой вариант. Transpose годится для того, чтоб поворачивать на 90 градусов в ту или другую сторону и, возможно, при этом отражать зеркально. Узко заточенный фильтр. Для произвольных углов - rotate.

filter_complex и видео из одной картинки

ffmpeg -i cutted2.mov -filter_complex "[0:v] fade type=in:start_time=0:duration=2:color=black" faded-start.mov 

рабочий пример видео из одной картинки.

ffmpeg -filter_complex aevalsrc=0 -loop 1 -i fbronin-papirus-black.png -t 5 start.mov

This is easiest to explain using an example:

ffmpeg -i input1.mp4 -i input2.webm -filter_complex \
"[0:v:0] [0:a:0] [1:v:0] [1:a:0] concat=n=2:v=1:a=1 [v] [a]" \
-map "[v]" -map "[a]" <encoding options> output.mkv

Мой заработавший вариант.

ffmpeg -i start.mov -i faded.mov -filter_complex \
"[0:v][0:a][1:v][1:a][0:v][0:a] concat=n=3:v=1:a=1:unsafe=1 [v] [a]" \
 -map "[v]" -map "[a]" -preset ultrafast  -y output.mp4

On the -filter_complex line, the following:

0:v:0] [0:a:0] [1:v:0] [1:a:0]
tells ffmpeg what streams to send to the concat filter; in this case, video stream 0 \[0:v:0\] and audio stream 0 \[0:a:0\] from input 0 (input1.mp4 in this example), and video stream 0 \[1:v:0\] and audio stream 0 \[1:v:0\] from input 1 (input2.webm).

В моём примере - второй раз повторяется набор \[0:v:0\] \[0:a:0\], потому что начало и конец файла одинаковы.

  • concat=n=2:v=1:a=1 [v] [a]:: This is the concat filter itself. n=2 is telling the filter that there are two input files; v=1 is telling it that there will be one video stream; a=1 is telling it that there will be one audio stream. [v] and [a] are names for the output streams to allow the rest of the ffmpeg line to use the output of the concat filter.
  • unsafe - на всякий случай )
  • Note that the single quotes around the whole filter section are required.
  • This tells ffmpeg to use the results of the concat filter rather than the streams directly from the input files.

Note that filters are incompatible with stream copying; you can't use -c copy with this method.

что-то давнее

  • alias recwebcam='ffmpeg -b:v 1000k -f video4linux2 -s 640x480 -i /dev/video0 -sameq -f alsa -i hw:1,0 -f avi '
  • alias recdesktop='ffmpeg -f x11grab -s 1920x1080 -r 8 -i :0.0 -sameq '

Правда, кажется, что-то тут не так - ибо хочет продолжать писать кадры, и обламывается.

  • ffmpeg -t 1 -f video4linux2 -s 640x480 -r 30 -i /dev/video0 foto.jpg

Ссылки


Если у вас есть мысли, комментарии, предложения или отклики по поводу этой страницы или этого цифрового сада в целом, напишите мне сообщение через Яндекс.Форму или на agnessa@agnessa.pp.ru. Мне ооочень интересно!

Задонатить.


An IndieWeb Webring 🕸💍