Up to date
This page is up to date for Godot 4.2
.
If you still find outdated information, please open an issue.
Воспроизведение видео¶
Godot supports video playback with the VideoStreamPlayer node.
Supported playback formats¶
Единственный поддерживаемый формат в ядре - Ogg Theora (не путать с Ogg Vorbis audio). Расширения могут обеспечить поддержку дополнительных форматов, но по состоянию на июль 2022 года таких расширений пока не существует.
H.264 и H.265 не могут поддерживаться в ядре Godot, поскольку оба они обременены патентами на программное обеспечение. AV1 не требует авторских отчислений, но он по-прежнему медленно декодируется на CPU, а аппаратная поддержка декодирования пока доступна не на всех используемых GPU.
WebM was supported in core in Godot 3.x, but support for it was removed in 4.0 as it was too buggy and difficult to maintain.
Примечание
Вы можете найти видео с расширениями .ogg
или .ogx
, которые являются общими расширениями для данных внутри контейнера Ogg.
Переименование расширений этих файлов в .ogv
может позволить импортировать видео в Godot. Однако не все файлы с расширениями .ogg
или .ogx
являются видео - некоторые из них могут содержать только аудио.
Setting up VideoStreamPlayer¶
Create a VideoStreamPlayer node using the Create New Node dialog.
Select the VideoStreamPlayer node in the scene tree dock, go to the inspector and load an
.ogv
file in the Stream property.Если у вас еще нет видео в формате Ogg Theora, перейдите к Рекомендуемые параметры кодировки Theora.
If you want the video to play as soon as the scene is loaded, check Autoplay in the inspector. If not, leave Autoplay disabled and call
play()
on the VideoStreamPlayer node in a script to start playback when desired.
Handling resizing and different aspect ratios¶
By default in Godot 4.0, the VideoStreamPlayer will automatically be resized to match the video's resolution. You can make it follow usual Control sizing by enabling Expand on the VideoStreamPlayer node.
To adjust how the VideoStreamPlayer node resizes depending on window size, adjust the anchors using the Layout menu at the top of the 2D editor viewport. However, this setup may not be powerful enough to handle all use cases, such as playing fullscreen videos without distorting the video (but with empty space on the edges instead). For more control, you can use an AspectRatioContainer node, which is designed to handle this kind of use case:
Добавьте узел AspectRatioContainer. Убедитесь, что он не является дочерним узлом какого-либо другого узла контейнера. Выберите узел AspectRatioContainer, затем установите для его Layout в верхней части 2D-редактора значение Full Rect. Установите Ratio в узле AspectRatioContainer в соответствии с соотношением сторон вашего видео. Вы можете использовать математические формулы в инспекторе, чтобы помочь себе. Не забудьте сделать один из операндов плавающей величиной. В противном случае результатом деления всегда будет целое число.
Once you've configured the AspectRatioContainer, reparent your VideoStreamPlayer node to be a child of the AspectRatioContainer node. Make sure Expand is enabled on the VideoStreamPlayer. Your video should now scale automatically to fit the whole screen while avoiding distortion.
См.также
See Multiple resolutions for more tips on supporting multiple aspect ratios in your project.
Отображение видео на 3D-поверхности¶
Using a VideoStreamPlayer node as a child of a SubViewport node, it's possible to display any 2D node on a 3D surface. For example, this can be used to display animated billboards when frame-by-frame animation would require too much memory.
This can be done with the following steps:
Create a SubViewport node. Set its size to match your video's size in pixels.
Create a VideoStreamPlayer node as a child of the SubViewport node and specify a video path in it. Make sure Expand is disabled, and enable Autoplay if needed.
Create a MeshInstance3D node with a PlaneMesh or QuadMesh resource in its Mesh property. Resize the mesh to match the video's aspect ratio (otherwise, it will appear distorted).
Create a new StandardMaterial3D resource in the Material Override property in the GeometryInstance3D section.
Enable Local To Scene in the StandardMaterial3D's Resource section (at the bottom). This is required before you can use a ViewportTexture in its Albedo Texture property.
In the StandardMaterial3D, set the Albedo > Texture property to New ViewportTexture. Edit the new resource by clicking it, then specify the path to the SubViewport node in the Viewport Path property.
Enable Albedo Texture Force sRGB in the StandardMaterial3D to prevent colors from being washed out.
If the billboard is supposed to emit its own light, set Shading Mode to Unshaded to improve rendering performance.
See Использовать Viewports and the GUI in 3D demo for more information on setting this up.
Looping a video¶
For looping a video, the Loop property can be enabled. This will seamlessly restart the video when it reaches its end.
Note that setting the project setting Video Delay Compensation to a non-zero value might cause your loop to not be seamless, because the synchronization of audio and video takes place at the start of each loop causing occasional missed frames. Set Video Delay Compensation in your project settings to 0 to avoid frame drop issues.
Условия декодирования видео и рекомендуемые разрешения¶
Декодирование видео выполняется на CPU, поскольку GPU не имеют аппаратного ускорения для декодирования видео Theora. Современные настольные процессоры могут декодировать видео Ogg Theora с разрешением 1440p @ 60 FPS или более, но мобильные процессоры низкого класса, скорее всего, не справятся с видео высокого разрешения.
Чтобы обеспечить плавное декодирование ваших видео на различном оборудовании:
При разработке игр для настольных платформ рекомендуется кодировать видео в формате 1080p (желательно с частотой 30 кадров в секунду). Большинство людей по-прежнему используют дисплеи с разрешением 1080p или ниже, поэтому кодирование видео с более высоким разрешением может не стоить увеличения размера файла и требований к процессору.
При разработке игр для мобильных или веб-платформ рекомендуется кодировать в формате 720p (предпочтительно с частотой 30 кадров в секунду или даже ниже). Визуальная разница между видео 720p и 1080p на мобильном устройстве обычно не так заметна.
Playback limitations¶
Текущая реализация воспроизведения видео в Godot имеет несколько ограничений:
Досмотр видео до определенной точки не поддерживается.
Changing playback speed is not supported. VideoStreamPlayer also won't follow Engine.time_scale.
Потоковая передача видео из URL-адреса не поддерживается.
Рекомендуемые параметры кодировки Theora¶
Небольшой совет: Не полагайтесь на встроенные программы экспортирования Ogg Theora (в большинстве случаев). Есть 2 причины, по которым вы, возможно, захотите использовать внешнюю программу для кодирования вашего видео:
Некоторые программы, такие как Blender, могут выполнять рендеринг в Ogg Theora. Однако предустановки качества по умолчанию обычно очень низкие по современным стандартам. Возможно, вы сможете увеличить параметры качества в используемой программе, но качество на выходе может оказаться ниже идеального (учитывая увеличенный размер файла). Обычно это означает, что программное обеспечение поддерживает кодирование только с постоянной скоростью передачи данных (CBR), а не с переменной скоростью передачи данных (VBR). В большинстве сценариев предпочтение следует отдавать кодированию VBR, поскольку оно обеспечивает лучшее соотношение качества и размера файла.
Другие программы совсем не могут рендерить в Ogg Theora.
В этом случае можно преобразовать видео в промежуточный высококачественный формат (например, высокобитрейтный H.264), а затем повторно закодировать его в Ogg Theora. В идеале для достижения максимального качества выходного видео Ogg Theora следует использовать в качестве промежуточного формата формат без потерь или без сжатия, но это может потребовать большого объема дискового пространства.
Популярные инструменты с открытым кодом, подходящие для этой цели - HandBrake (С графическим интерфейсом) и FFmpeg (С консольным интерфейсом).
Here are example FFmpeg commands to convert a MP4 video to Ogg Theora. Since FFmpeg supports a lot of input formats, you should be able to use the commands below with almost any input video format (AVI, MOV, WebM, …).
Примечание
Make sure your copy of FFmpeg is compiled with libtheora and libvorbis support.
You can check this by running ffmpeg
without any arguments, then looking
at the configuration:
line in the command output.
Балансирует между качеством и размером файла¶
Уровень качества видео (-q:v
) должен находиться в диапазоне от 1
до 10
. Качество 6
является хорошим компромиссом между качеством и размером файла. При кодировании в высоком разрешении (например, 1440p или 4K) для сохранения приемлемого размера файла, вероятно, потребуется уменьшить -q:v
до 5
. Поскольку плотность пикселей на видео с разрешением 1440p или 4K выше, пресеты с более низким качеством при высоком разрешении будут выглядеть так же или даже лучше, чем видео с низким разрешением.
The audio quality level (-q:a
) must be between -1
and 10
. Quality
6
provides a good compromise between quality and file size. In contrast to
video quality, increasing audio quality doesn't increase the output file size
nearly as much. Therefore, if you want the cleanest audio possible, you can
increase this to 9
to get perceptually lossless audio. This is especially
valuable if your input file already uses lossy audio compression. Higher quality
audio does increase the CPU usage of the decoder, so it might lead to audio
dropouts in case of high system load. See
this page
for a table listing Ogg Vorbis audio quality presets and their respective
variable bitrates.
FFmpeg: Конвертирование с сохранением исходного разрешения видео¶
Следующая команда преобразует видео с сохранением его исходного разрешения. Битрейт видео и аудио будет изменяться, чтобы обеспечить максимальное качество и одновременно сэкономить место в тех частях видео/аудио, которые не требуют высокого битрейта (например, в статичных сценах).
ffmpeg -i input.mp4 -q:v 6 -q:a 6 output.ogv
FFmpeg: Изменить размер видео, затем конвертировать¶
Следующая команда изменяет разрешение видео до 720 пикселей в высоту(720p), при сохранении существующего соотношения сторон. Это поможет значительно снизить размер файла, если он записан с разрешением выше чем 720p:
ffmpeg -i input.mp4 -vf "scale=-1:720" -q:v 6 -q:a 6 output.ogv
Chroma Key Videos¶
Chroma key, commonly known as the "green screen" or "blue screen" effect, allows you to remove a specific color from an image or video and replace it with another background. This effect is widely used in video production to composite different elements together seamlessly.
We will achieve the chroma key effect by writing a custom shader in GDScript and using a VideoStreamPlayer node to display the video content.
Scene Setup¶
Ensure that the scene contains a VideoStreamPlayer node to play the video and a Control node to hold the UI elements for controlling the chroma key effect.
Writing the Custom Shader¶
To implement the chroma key effect, follow these steps:
Select the VideoStreamPlayer node in the scene and go to its properties. Under CanvasItem > Material, create a new shader named "ChromaKeyShader.gdshader."
In the "ChromaKeyShader.gdshader" file, write the custom shader code as shown below:
shader_type canvas_item;
# Uniform variables for chroma key effect
uniform vec3 chroma_key_color : source_color = vec3(0.0, 1.0, 0.0);
uniform float pickup_range : hint_range(0.0, 1.0) = 0.1;
uniform float fade_amount : hint_range(0.0, 1.0) = 0.1;
void fragment() {
# Get the color from the texture at the given UV coordinates
vec4 color = texture(TEXTURE, UV);
# Calculate the distance between the current color and the chroma key color
float distance = length(color.rgb - chroma_key_color);
# If the distance is within the pickup range, discard the pixel
# the lesser the distance more likely the colors are
if (distance <= pickup_range) {
discard;
}
# Calculate the fade factor based on the pickup range and fade amount
float fade_factor = smoothstep(pickup_range, pickup_range + fade_amount, distance);
# Set the output color with the original RGB values and the calculated fade factor
COLOR = vec4(color.rgb, fade_factor);
}
The shader uses the distance calculation to identify pixels close to the chroma key color and discards them, effectively removing the selected color. Pixels that are slightly further away from the chroma key color are faded based on the fade_factor, blending them smoothly with the surrounding colors. This process creates the desired chroma key effect, making it appear as if the background has been replaced with another image or video.
The code above represents a simple demonstration of the Chroma Key shader, and users can customize it according to their specific requirements.
UI Controls¶
To allow users to manipulate the chroma key effect in real-time, we created sliders in the Control node. The Control node's script contains the following functions:
extends Control
func _on_color_picker_button_color_changed(color):
# Update the "chroma_key_color" shader parameter of the VideoStreamPlayer's material
$VideoStreamPlayer.material.set("shader_parameter/chroma_key_color", color)
func _on_h_slider_value_changed(value):
# Update the "pickup_range" shader parameter of the VideoStreamPlayer's material
$VideoStreamPlayer.material.set("shader_parameter/pickup_range", value)
func _on_h_slider_2_value_changed(value):
# Update the "fade_amount" shader parameter of the VideoStreamPlayer's material
$VideoStreamPlayer.material.set("shader_parameter/fade_amount", value)
func _on_video_stream_player_finished():
# Restart the video playback when it's finished
$VideoStreamPlayer.play()
also make sure that the range of the sliders are appropriate, our settings are :
Signal Handling¶
Connect the appropriate signal from the UI elements to the Control node's script. you created in the Control node's script to control the chroma key effect. These signal handlers will update the shader's uniform variables in response to user input.
Save and run the scene to see the chroma key effect in action! With the provided UI controls, you can now adjust the chroma key color, pickup range, and fade amount in real-time, achieving the desired chroma key functionality for your video content.