Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/servers/movie_writer/movie_writer.cpp
21981 views
1
/**************************************************************************/
2
/* movie_writer.cpp */
3
/**************************************************************************/
4
/* This file is part of: */
5
/* GODOT ENGINE */
6
/* https://godotengine.org */
7
/**************************************************************************/
8
/* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
9
/* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
10
/* */
11
/* Permission is hereby granted, free of charge, to any person obtaining */
12
/* a copy of this software and associated documentation files (the */
13
/* "Software"), to deal in the Software without restriction, including */
14
/* without limitation the rights to use, copy, modify, merge, publish, */
15
/* distribute, sublicense, and/or sell copies of the Software, and to */
16
/* permit persons to whom the Software is furnished to do so, subject to */
17
/* the following conditions: */
18
/* */
19
/* The above copyright notice and this permission notice shall be */
20
/* included in all copies or substantial portions of the Software. */
21
/* */
22
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
23
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
24
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
25
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
26
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
27
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
28
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
29
/**************************************************************************/
30
31
#include "movie_writer.h"
32
#include "core/config/project_settings.h"
33
#include "core/io/dir_access.h"
34
#include "core/os/time.h"
35
#include "scene/main/window.h"
36
#include "servers/audio/audio_driver_dummy.h"
37
#include "servers/display/display_server.h"
38
#include "servers/rendering/rendering_server.h"
39
40
MovieWriter *MovieWriter::writers[MovieWriter::MAX_WRITERS];
41
uint32_t MovieWriter::writer_count = 0;
42
43
void MovieWriter::add_writer(MovieWriter *p_writer) {
44
ERR_FAIL_COND(writer_count == MAX_WRITERS);
45
writers[writer_count++] = p_writer;
46
}
47
48
MovieWriter *MovieWriter::find_writer_for_file(const String &p_file) {
49
for (int32_t i = writer_count - 1; i >= 0; i--) { // More recent last, to have override ability.
50
if (writers[i]->handles_file(p_file)) {
51
return writers[i];
52
}
53
}
54
return nullptr;
55
}
56
57
uint32_t MovieWriter::get_audio_mix_rate() const {
58
uint32_t ret = 48000;
59
GDVIRTUAL_CALL(_get_audio_mix_rate, ret);
60
return ret;
61
}
62
AudioServer::SpeakerMode MovieWriter::get_audio_speaker_mode() const {
63
AudioServer::SpeakerMode ret = AudioServer::SPEAKER_MODE_STEREO;
64
GDVIRTUAL_CALL(_get_audio_speaker_mode, ret);
65
return ret;
66
}
67
68
Error MovieWriter::write_begin(const Size2i &p_movie_size, uint32_t p_fps, const String &p_base_path) {
69
Error ret = ERR_UNCONFIGURED;
70
GDVIRTUAL_CALL(_write_begin, p_movie_size, p_fps, p_base_path, ret);
71
return ret;
72
}
73
74
Error MovieWriter::write_frame(const Ref<Image> &p_image, const int32_t *p_audio_data) {
75
Error ret = ERR_UNCONFIGURED;
76
GDVIRTUAL_CALL(_write_frame, p_image, p_audio_data, ret);
77
return ret;
78
}
79
80
void MovieWriter::write_end() {
81
GDVIRTUAL_CALL(_write_end);
82
}
83
84
bool MovieWriter::handles_file(const String &p_path) const {
85
bool ret = false;
86
GDVIRTUAL_CALL(_handles_file, p_path, ret);
87
return ret;
88
}
89
90
void MovieWriter::get_supported_extensions(List<String> *r_extensions) const {
91
Vector<String> exts;
92
GDVIRTUAL_CALL(_get_supported_extensions, exts);
93
for (int i = 0; i < exts.size(); i++) {
94
r_extensions->push_back(exts[i]);
95
}
96
}
97
98
void MovieWriter::begin(const Size2i &p_movie_size, uint32_t p_fps, const String &p_base_path) {
99
project_name = GLOBAL_GET("application/config/name");
100
movie_size = p_movie_size;
101
102
print_line(vformat(U"Movie Maker mode enabled, recording movie in %s×%s @ %d FPS...", movie_size.width, movie_size.height, p_fps));
103
104
// Check for available disk space and warn the user if needed.
105
Ref<DirAccess> dir = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
106
String path = p_base_path.get_base_dir();
107
if (path.is_relative_path()) {
108
path = "res://" + path;
109
}
110
dir->open(path);
111
if (dir->get_space_left() < 10 * Math::pow(1024.0, 3.0)) {
112
// Less than 10 GiB available.
113
WARN_PRINT(vformat("Current available space on disk is low (%s). MovieWriter will fail during movie recording if the disk runs out of available space.", String::humanize_size(dir->get_space_left())));
114
}
115
116
cpu_time = 0.0f;
117
gpu_time = 0.0f;
118
encoding_time_usec = 0;
119
120
mix_rate = get_audio_mix_rate();
121
AudioDriverDummy::get_dummy_singleton()->set_mix_rate(mix_rate);
122
AudioDriverDummy::get_dummy_singleton()->set_speaker_mode(AudioDriver::SpeakerMode(get_audio_speaker_mode()));
123
fps = p_fps;
124
if ((mix_rate % fps) != 0) {
125
WARN_PRINT("MovieWriter's audio mix rate (" + itos(mix_rate) + ") can not be divided by the recording FPS (" + itos(fps) + "). Audio may go out of sync over time.");
126
}
127
128
audio_channels = AudioDriverDummy::get_dummy_singleton()->get_channels();
129
audio_mix_buffer.resize(mix_rate * audio_channels / fps);
130
131
write_begin(movie_size, p_fps, p_base_path);
132
}
133
134
void MovieWriter::_bind_methods() {
135
ClassDB::bind_static_method("MovieWriter", D_METHOD("add_writer", "writer"), &MovieWriter::add_writer);
136
137
GDVIRTUAL_BIND(_get_audio_mix_rate)
138
GDVIRTUAL_BIND(_get_audio_speaker_mode)
139
140
GDVIRTUAL_BIND(_handles_file, "path")
141
142
GDVIRTUAL_BIND(_write_begin, "movie_size", "fps", "base_path")
143
GDVIRTUAL_BIND(_write_frame, "frame_image", "audio_frame_block")
144
GDVIRTUAL_BIND(_write_end)
145
146
GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/movie_writer/mix_rate", PROPERTY_HINT_RANGE, "8000,192000,1,suffix:Hz"), 48000);
147
GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/movie_writer/speaker_mode", PROPERTY_HINT_ENUM, "Stereo,3.1,5.1,7.1"), 0);
148
GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "editor/movie_writer/video_quality", PROPERTY_HINT_RANGE, "0.0,1.0,0.01"), 0.75);
149
GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/movie_writer/audio_bit_depth", PROPERTY_HINT_ENUM, "16:16,32:32"), 16);
150
GLOBAL_DEF(PropertyInfo(Variant::FLOAT, "editor/movie_writer/ogv/audio_quality", PROPERTY_HINT_RANGE, "-0.1,1.0,0.01"), 0.5);
151
GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/movie_writer/ogv/encoding_speed", PROPERTY_HINT_ENUM, "Fastest (Lowest Efficiency):4,Fast (Low Efficiency):3,Slow (High Efficiency):2,Slowest (Highest Efficiency):1"), 4);
152
GLOBAL_DEF(PropertyInfo(Variant::INT, "editor/movie_writer/ogv/keyframe_interval", PROPERTY_HINT_RANGE, "1,1024,1"), 64);
153
154
// Used by the editor.
155
GLOBAL_DEF_BASIC("editor/movie_writer/movie_file", "");
156
GLOBAL_DEF_BASIC("editor/movie_writer/disable_vsync", false);
157
GLOBAL_DEF_BASIC(PropertyInfo(Variant::INT, "editor/movie_writer/fps", PROPERTY_HINT_RANGE, "1,300,1,suffix:FPS"), 60);
158
}
159
160
void MovieWriter::set_extensions_hint() {
161
RBSet<String> found;
162
for (uint32_t i = 0; i < writer_count; i++) {
163
List<String> extensions;
164
writers[i]->get_supported_extensions(&extensions);
165
for (const String &ext : extensions) {
166
found.insert(ext);
167
}
168
}
169
170
String ext_hint;
171
172
for (const String &S : found) {
173
if (ext_hint != "") {
174
ext_hint += ",";
175
}
176
ext_hint += "*." + S;
177
}
178
ProjectSettings::get_singleton()->set_custom_property_info(PropertyInfo(Variant::STRING, "editor/movie_writer/movie_file", PROPERTY_HINT_GLOBAL_SAVE_FILE, ext_hint));
179
}
180
181
void MovieWriter::add_frame() {
182
const int movie_time_seconds = Engine::get_singleton()->get_frames_drawn() / fps;
183
const int frame_remainder = Engine::get_singleton()->get_frames_drawn() % fps;
184
const String movie_time = vformat("%s:%s:%s:%s",
185
String::num(movie_time_seconds / 3600, 0).pad_zeros(2),
186
String::num((movie_time_seconds % 3600) / 60, 0).pad_zeros(2),
187
String::num(movie_time_seconds % 60, 0).pad_zeros(2),
188
String::num(frame_remainder, 0).pad_zeros(2));
189
190
Window *main_window = Window::get_from_id(DisplayServer::MAIN_WINDOW_ID);
191
if (main_window) {
192
main_window->set_title(vformat("MovieWriter: Frame %d (time: %s) - %s", Engine::get_singleton()->get_frames_drawn(), movie_time, project_name));
193
}
194
195
RID main_vp_rid = RenderingServer::get_singleton()->viewport_find_from_screen_attachment(DisplayServer::MAIN_WINDOW_ID);
196
RID main_vp_texture = RenderingServer::get_singleton()->viewport_get_texture(main_vp_rid);
197
Ref<Image> vp_tex = RenderingServer::get_singleton()->texture_2d_get(main_vp_texture);
198
199
if (vp_tex->get_size() != movie_size) {
200
// Resize the texture to the output resolution if it differs from the current viewport size.
201
// This ensures all frames have the same resolution, as not all video formats and players
202
// support resolution changes during playback.
203
204
const float src_aspect = vp_tex->get_size().aspect();
205
const float dst_aspect = movie_size.aspect();
206
207
int crop_width = vp_tex->get_size().width;
208
int crop_height = vp_tex->get_size().height;
209
int crop_x = 0;
210
int crop_y = 0;
211
212
// If the aspect ratio differs, crop the image to cover the base resolution's aspect ratio
213
// in a way similar to `TextureRect.STRETCH_KEEP_ASPECT_COVERED`.
214
if (src_aspect > dst_aspect) {
215
// Source is wider, crop horizontally.
216
crop_width = int(vp_tex->get_size().height * dst_aspect);
217
crop_x = (vp_tex->get_size().width - crop_width) / 2;
218
vp_tex->crop_from_point(crop_x, crop_y, crop_width, crop_height);
219
} else if (src_aspect < dst_aspect) {
220
// Source is taller, crop vertically.
221
crop_height = int(vp_tex->get_size().width / dst_aspect);
222
crop_y = (vp_tex->get_size().height - crop_height) / 2;
223
vp_tex->crop_from_point(crop_x, crop_y, crop_width, crop_height);
224
}
225
226
vp_tex->resize(movie_size.width, movie_size.height, Image::INTERPOLATE_BILINEAR);
227
}
228
229
if (RenderingServer::get_singleton()->viewport_is_using_hdr_2d(main_vp_rid)) {
230
vp_tex->convert(Image::FORMAT_RGBA8);
231
vp_tex->linear_to_srgb();
232
}
233
234
RenderingServer::get_singleton()->viewport_set_measure_render_time(main_vp_rid, true);
235
cpu_time += RenderingServer::get_singleton()->viewport_get_measured_render_time_cpu(main_vp_rid);
236
cpu_time += RenderingServer::get_singleton()->get_frame_setup_time_cpu();
237
gpu_time += RenderingServer::get_singleton()->viewport_get_measured_render_time_gpu(main_vp_rid);
238
239
AudioDriverDummy::get_dummy_singleton()->mix_audio(mix_rate / fps, audio_mix_buffer.ptr());
240
241
uint64_t encoding_start_usec = Time::get_singleton()->get_ticks_usec();
242
write_frame(vp_tex, audio_mix_buffer.ptr());
243
uint64_t encoding_end_usec = Time::get_singleton()->get_ticks_usec();
244
encoding_time_usec += encoding_end_usec - encoding_start_usec;
245
}
246
247
void MovieWriter::end() {
248
uint64_t encoding_start_usec = Time::get_singleton()->get_ticks_usec();
249
write_end();
250
uint64_t encoding_end_usec = Time::get_singleton()->get_ticks_usec();
251
encoding_time_usec += encoding_end_usec - encoding_start_usec;
252
253
// Print a report with various statistics.
254
print_line("--------------------------------------------------------------------------------");
255
String movie_path = Engine::get_singleton()->get_write_movie_path();
256
if (movie_path.is_relative_path()) {
257
// Print absolute path to make finding the file easier,
258
// and to make it clickable in terminal emulators that support this.
259
movie_path = ProjectSettings::get_singleton()->globalize_path("res://").path_join(movie_path);
260
}
261
print_line(vformat("Done recording movie at path: %s", movie_path));
262
263
const int movie_time_seconds = Engine::get_singleton()->get_frames_drawn() / fps;
264
const int frame_remainder = Engine::get_singleton()->get_frames_drawn() % fps;
265
const String movie_time = vformat("%s:%s:%s:%s",
266
String::num(movie_time_seconds / 3600, 0).pad_zeros(2),
267
String::num((movie_time_seconds % 3600) / 60, 0).pad_zeros(2),
268
String::num(movie_time_seconds % 60, 0).pad_zeros(2),
269
String::num(frame_remainder, 0).pad_zeros(2));
270
271
const int real_time_seconds = Time::get_singleton()->get_ticks_msec() / 1000;
272
const String real_time = vformat("%s:%s:%s",
273
String::num(real_time_seconds / 3600, 0).pad_zeros(2),
274
String::num((real_time_seconds % 3600) / 60, 0).pad_zeros(2),
275
String::num(real_time_seconds % 60, 0).pad_zeros(2));
276
277
print_line(vformat("%d frames at %d FPS (movie length: %s), recorded in %s (%d%% of real-time speed).", Engine::get_singleton()->get_frames_drawn(), fps, movie_time, real_time, (float(MAX(1, movie_time_seconds)) / MAX(1, real_time_seconds)) * 100));
278
print_line(vformat("CPU render time: %.2f seconds (average: %.2f ms/frame)", cpu_time / 1000, cpu_time / Engine::get_singleton()->get_frames_drawn()));
279
print_line(vformat("GPU render time: %.2f seconds (average: %.2f ms/frame)", gpu_time / 1000, gpu_time / Engine::get_singleton()->get_frames_drawn()));
280
print_line(vformat("Encoding time: %.2f seconds (average: %.2f ms/frame)", encoding_time_usec / 1000000.f, encoding_time_usec / 1000.f / Engine::get_singleton()->get_frames_drawn()));
281
print_line("--------------------------------------------------------------------------------");
282
}
283
284