- Keep quality after drawtext in ffmpeg [duplicate]
- 1 Answer 1
- Lossless
- Example using the encoder huffyuv
- Example using the encoder libx264
- Visually lossless
- Chroma subsampling
- Subtitles
- ffmpeg create blank screen with text video
- 1 Answer 1
- drawtext vs subtitles
- drawtext filter examples
- Add text to solid color background
- With audio file
- With a transparent box behind text
- Multiple lines
- Method 1: Multiple drawtext instances
- Method 2: External text file
- Method 3: Line break in command
- Positions
- subtitles filter example with audio
- Текстовые выражения параметров ffmpeg drawtext
- ffmpeg failing to expand drawtext
- 1 Answer 1
- FFMPEG и вывод текущего времени, как сделать?
Keep quality after drawtext in ffmpeg [duplicate]
I am trying to use ffmpeg to put a subtitle in an avi video. I use this command to do it:
The output of ffmpeg console is :
But my input video is 135 MB and the output is only 613 KB. How i could keep the same quality of video?
1 Answer 1
Filtering requires re-encoding, but there are several options to «keep the same quality», or at least provide a quality that is good enough.
Lossless
To keep the same quality one option is to use a lossless format.
Example using the encoder huffyuv
Example using the encoder libx264
A -crf value of 0 will initiate lossless mode for this encoder. See the FFmpeg and x264 Encoding Guide for more info.
Visually lossless
A second option is to use a visually lossless format. This is not technically lossless, but it will look lossless (or nearly so) and provide a much smaller file size. A -crf value of
18 is generally considered to be visually lossless. Reduce the value if it does not provide an adequate quality. Again, see the FFmpeg and x264 Encoding Guide for more info.
Chroma subsampling
You may need to adjust the chroma subsampling for the above example if you want it to play in non-FFmpeg based players because, depending on the input, ffmpeg will attempt to minimize or avoid chroma subsampling. However, note that this may cause color loss or artifacts.
The audio is simply stream copied instead of re-encoded in these examples.
Subtitles
A third option is to mux a subtitles stream into the video:
This has the advantage of not touching the video and audio at all and any sane player worth using will allow you to turn the subtitles on or off during playback.
ffmpeg create blank screen with text video
I would like to create a video consisting of some text. The video will only be 0.5 seconds long. The background should just be some colour, I am able to create such video from a photo, but cant find anywhere how this could be done without a photo, just using text to create such video.
Can you help me ? Thanks in advance
1 Answer 1
drawtext vs subtitles
This can be done using the drawtext or subtitles filters.
drawtext is simpler, but subtitles has much better styling and timing options. subtitles can automatically wrap the text while drawtext cannot.
drawtext filter examples
Add text to solid color background
Using the color filter for the background and the drawtext filter for the text. Example for a 320×240, 10 second, 25 fps, blue background. Text is size 30, colored white, and centered.
With audio file
Same as above, but video will automatically match audio duration by removing duration=10 and adding -shortest :
With a transparent box behind text
Another example with a white box behind the text at 25% opacity with 5 pixel padding:
Multiple lines
It’s easier to center the two lines with multiple drawtext instances (left image). Right image is from the external file and line break examples.
There are 3 methods. You can chain together two drawtext filters, or reference an external text file with the textfile option, or add the line break in the command.
Alternatively, see the example below using the subtitles filter. This filter will automatically wrap long text.
Method 1: Multiple drawtext instances
Method 2: External text file
The contents of the text file, text.txt , looks like this:
The ffmpeg command:
Method 3: Line break in command
Positions
- Top left: x=0:y=0 (with 10 pixel padding x=10:y=10 )
- Top center: x=(w-text_w)/2:y=0 (with 10 px padding x=(w-text_w)/2:y=10 )
- Top right: x=w-tw:y=0 (with 10 px padding: x=w-tw-10:y=10 )
- Centered: x=(w-text_w)/2:y=(h-text_h)/2
- Bottom left: x=0:y=h-th (with 10 px padding: x=10:y=h-th-10 )
- Bottom center: x=(w-text_w)/2:y=h-th (with 10 px padding: x=(w-text_w)/2:y=h-th-10 )
- Bottom right: x=w-tw:y=h-th (with 10 px padding: x=w-tw-10:y=h-th-10 )
subtitles filter example with audio
Using the color filter for the background and the subtitles filter for the text.
First, create SRT (SubRip) file. This example sets the duration to 10 hours. The duration doesn’t really matter: it just needs to be longer than the audio file duration.
Then run ffmpeg :
Alternatively, use Aegisub to create ASS (Advanced SubStation Alpha) subtitles and you won’t have to use force_style . Downside is that ASS is a much more complicated format than SRT.
If you want to use force_style refer to the Format and Style lines in an ASS file to get an idea of how to use more force_style options, and also see Aegisub Manual — Ass Tags for advanced formatting.
Текстовые выражения параметров ffmpeg drawtext
Я пытаюсь написать текст на видео таким образом, чтобы текст «записывался сам» — буква за буквой.
Чтобы сделать это, я смог сделать что-то вроде этого:
Это заменяет текст на экране новым каждые полторы секунды, добавляя новый символ. ( a изменяется на ab ). Очевидно, что если тексты длинны, эта строка будет очень длинной.
Я смог сделать что-то похожее и короче:
Где сам текст является выражением, зависящим от времени. Однако это работает только для чисел: 1 изменяется на 12 (игнорируя числа после десятичной точки на данный момент).
Now the issue is that if I try to do the same expression for texts ( a->ab ) this fails. and I get:
Выражение ‘if (gt (t, 1.5), ab, a)’ для функции расширения текста expr недопустимо.
Возникает вопрос: возможно ли, чтобы выражение возвращало фактический текст после расширения и не только числа ?.
Заранее благодарим за помощь!
Хорошо, это можно сделать, но это неэлегантно и имеет ограничения, которые делают это, в конце концов, не стоит. Ограничение заключается в том, что это только правильно работает с шрифтами с фиксированной шириной. И из-за неподвижной ошибки в ffmpeg, это будет выглядеть несколько уродливо.
- создать непрозрачный холст. Я использовал всю ширину в качестве моего видеовхода и достаточную высоту, чтобы содержать текст, и я использовал ту же частоту кадров, что и мое видео.
- На этом холсте нарисуйте текст один раз. Основной метод здесь — оживить окно обрезки. Поэтому, если ваш текст имеет длину 5 символов, ваша строка печати text = ‘1 12 123 1234 12345’ . Идея состоит в том, что ширина обрезки равна полной ширине строки, а источник урожая периодически меняет ширину одной строки, тем самым моделируя типизацию, поскольку каждая новая обрезанная область содержит один дополнительный символ. Итак, первые 5 пробелов для 5 символов, затем после первого 1 есть четыре пробела для прохода до полной ширины строки, тогда текст 2-го этапа следует с двумя символами и тремя пробелами , и так далее. Я указал цветовое пространство RGBA, так как он, казалось, обеспечивал лучшие результаты на шаге keying дальше.
- Теперь холст с текстом на нем обрезается. Ширина — это полная ширина строки, и я сохранил ту же высоту, но пока она не вырезает текст, не имеет значения. Смещение X урожая анимируется следующим образом: StringWidth * целочисленная часть (время, деленное на период) . Это сдвигает окно обрезки прямо на одну ширину строки после каждого периода, то есть 0,5 секунды в этом случае. Теперь это заключено в минимальную функцию, потому что мы хотим, чтобы обрезка оставалась неподвижной после того, как были напечатаны все символы. Итак, второе значение: stringWidth * (no of characters — 1) . Y не анимируется, так как это только одна строка.
- Следующая часть делает его уродливым. Из-за ошибки я сохранил фон непрозрачным. Итак, теперь он должен быть установлен на цветности. Фильтр ищет белый цвет BG и выбирает только этот цвет ( 0.01 ) и полностью смешивает его. Я надеялся сгладить края. Но не работает очень хорошо.
- Настройки позволяют установить задержку в секундах. Первый символ появится в delay + period seconds.
- Наконец, мы просто накладываем результат на видео.
ffmpeg failing to expand drawtext
I am trying to overlay a seconds:milliseconds timestamp on my video, but I have been breaking my head over this for some hours without any result. If I write:
the %
Please note that I have read a ton of guides around the web (ffmpeg docs/guides/wikis, stackoverflow, blogs, etc.) on this timestamp overlay stuff, but none of the solutions/syntaxes work: it simply overlays the literal text.
- using Windows 7×64 and TCC/LE
- ffmpeg Zeranoe build version git-12a419d (2015-11-23)
The full output log:
1 Answer 1
Remove the apostrophes around %
(I also removed the spaces in the -vf parameter, because they are not neccessary.)
You see, the Unix shell but also the Windows commandline make some changes to the commands, and that’s why you needed to repeat the backslash like this: \\ . This can get complicated and confusing. Each platform is a little bit different, so it’s difficult to give you a working solution without some experimenting. Currently I don’t have access to a Windows commandline with a working ffmpeg installation, so I could not test this solution. But I know that percent signs % are treated specially. It seems that it got eaten by your command line, and that’s why you see a literal
Edit: As the OP added that he used TCC/LE as shell, I proposed doubling the percent sign, like this:
This solution was also discussed in the StackOverflow answer mentioned above.
FFMPEG и вывод текущего времени, как сделать?
Нужно захватить через ffmpeg web-камеру в опеределенный момент и наложить на нее текст. Сам текст наложить получается, но кроме текста нужно добавить текущую дату и время.
. Вместо %T пробовал и %X
Вместо времени выводится буква T. Подскажите что я делаю не так или тыркните ссылкой в подробный рабочий пример, я уже много перепробовал, в том числе и с pts.
- Вопрос задан более трёх лет назад
- 948 просмотров
Ответ такой (вдруг пригодится кому, получил фактически подбором, но чуть чуть помогли на форуме ffmpeg):
1. Все параметры запихиваем в перменные (обратите внимание на запись переменных формата strtime (3)
2. Формируем строку и уже ее передаем в опцию ffmpeg:
3. Вставляем полученную переменную в опцию ffmpeg после ключа -vf
Спасибо, Moskus.
Дополнительная литература: [1] [2]
oldTV, про формат — я говорил по поводу того, что у вас было ‘ %
С экранированием символов — вечный геморрой. Я бы, на вашем месте, потренировался бы сначала на кошках, то есть написал бы минимальную команду только с наложением текста и без остальных наворотов, чтобы быть уверенным в том, что именно не работает.
Например, совершенно непонятно, видит ли ffmpeg ваш шрифт, или нет.
Вот вам еще пара кусков кода для образца:
(это точно работало в Windows)
https://trac.ffmpeg.org/ticket/4836 — багрепорт
Также, разные люди жалуются, что разные макросы strftime иногда не работают вообще.
Moskus, шрифт, конечно, русский, и он для текста по русский нормально не работает, его как то надо кодировать. Как — пока тоже не понятно. Но главное, что в сути задачи текст нужен английский. И он работает. Также работает команда timecode=’00\:00\:00\:00′ , которая показывает сколько времени прошло. Но она не нужна, нужно локальное время и дата.
Видимо проблема не в экранировании символов, а в параметре localtime, которое для русской Windows какое то другое. Это проявляется, например, когда в строке времени есть %s, который дает ошибку. Без него работает, но выводит текст, а не локальное время. Возможно надо как то %Ч:%М:%С, но тогда нужно перекодировать символы.
Пример выше не работает. Строка ‘%