Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
godotengine
GitHub Repository: godotengine/godot
Path: blob/master/modules/theora/editor/movie_writer_ogv.cpp
10278 views
1
/**************************************************************************/
2
/* movie_writer_ogv.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_ogv.h"
32
33
#include "core/config/project_settings.h"
34
#include "rgb2yuv.h"
35
36
void MovieWriterOGV::push_audio(const int32_t *p_audio_data) {
37
// Read and process more audio.
38
float **vorbis_buffer = vorbis_analysis_buffer(&vd, audio_frames);
39
40
// Deinterleave samples.
41
uint32_t count = 0;
42
for (uint32_t i = 0; i < audio_frames; i++) {
43
for (uint32_t j = 0; j < audio_ch; j++) {
44
vorbis_buffer[j][i] = p_audio_data[count] / 2147483647.f;
45
count++;
46
}
47
}
48
49
vorbis_analysis_wrote(&vd, audio_frames);
50
}
51
52
void MovieWriterOGV::pull_audio(bool p_last) {
53
ogg_packet op;
54
55
while (vorbis_analysis_blockout(&vd, &vb) > 0) {
56
// Analysis, assume we want to use bitrate management.
57
vorbis_analysis(&vb, nullptr);
58
vorbis_bitrate_addblock(&vb);
59
60
// Weld packets into the bitstream.
61
while (vorbis_bitrate_flushpacket(&vd, &op) > 0) {
62
ogg_stream_packetin(&vo, &op);
63
}
64
}
65
66
if (p_last) {
67
vorbis_analysis_wrote(&vd, 0);
68
pull_audio();
69
}
70
}
71
72
void MovieWriterOGV::push_video(const Ref<Image> &p_image) {
73
PackedByteArray data = p_image->get_data();
74
if (p_image->get_format() == Image::FORMAT_RGBA8) {
75
rgba2yuv420(y, u, v, data.ptrw(), p_image->get_width(), p_image->get_height());
76
} else {
77
rgb2yuv420(y, u, v, data.ptrw(), p_image->get_width(), p_image->get_height());
78
}
79
th_encode_ycbcr_in(td, ycbcr);
80
}
81
82
void MovieWriterOGV::pull_video(bool p_last) {
83
ogg_packet op;
84
85
int ret = 0;
86
do {
87
ret = th_encode_packetout(td, p_last, &op);
88
if (ret > 0) {
89
ogg_stream_packetin(&to, &op);
90
}
91
} while (ret > 0);
92
}
93
94
uint32_t MovieWriterOGV::get_audio_mix_rate() const {
95
return mix_rate;
96
}
97
98
AudioServer::SpeakerMode MovieWriterOGV::get_audio_speaker_mode() const {
99
return speaker_mode;
100
}
101
102
bool MovieWriterOGV::handles_file(const String &p_path) const {
103
return p_path.get_extension().to_lower() == "ogv";
104
}
105
106
void MovieWriterOGV::get_supported_extensions(List<String> *r_extensions) const {
107
r_extensions->push_back("ogv");
108
}
109
110
Error MovieWriterOGV::write_begin(const Size2i &p_movie_size, uint32_t p_fps, const String &p_base_path) {
111
ERR_FAIL_COND_V_MSG((p_movie_size.width & 1) || (p_movie_size.height & 1), ERR_UNAVAILABLE, "Both video dimensions must be even.");
112
base_path = p_base_path.get_basename();
113
if (base_path.is_relative_path()) {
114
base_path = "res://" + base_path;
115
}
116
base_path += ".ogv";
117
118
f = FileAccess::open(base_path, FileAccess::WRITE_READ);
119
ERR_FAIL_COND_V(f.is_null(), ERR_CANT_OPEN);
120
121
fps = p_fps;
122
123
audio_ch = 2;
124
switch (speaker_mode) {
125
case AudioServer::SPEAKER_MODE_STEREO:
126
audio_ch = 2;
127
break;
128
case AudioServer::SPEAKER_SURROUND_31:
129
audio_ch = 4;
130
break;
131
case AudioServer::SPEAKER_SURROUND_51:
132
audio_ch = 6;
133
break;
134
case AudioServer::SPEAKER_SURROUND_71:
135
audio_ch = 8;
136
break;
137
}
138
audio_frames = mix_rate / fps;
139
140
// Set up Ogg output streams.
141
srand(time(nullptr));
142
ogg_stream_init(&to, rand()); // Video.
143
ogg_stream_init(&vo, rand()); // Audio.
144
145
// Initialize Vorbis audio encoding.
146
vorbis_info_init(&vi);
147
int ret = vorbis_encode_init_vbr(&vi, audio_ch, mix_rate, audio_quality);
148
ERR_FAIL_COND_V_MSG(ret, ERR_UNAVAILABLE, "The Ogg Vorbis encoder couldn't set up a mode according to the requested quality or bitrate.");
149
150
vorbis_comment_init(&vc);
151
vorbis_analysis_init(&vd, &vi);
152
vorbis_block_init(&vd, &vb);
153
154
// Set up Theora encoder.
155
// Theora has a divisible-by-16 restriction for the encoded frame size
156
// scale the picture size up to the nearest /16 and calculate offsets.
157
int pic_w = p_movie_size.width;
158
int pic_h = p_movie_size.height;
159
int frame_w = (pic_w + 15) & ~0xF;
160
int frame_h = (pic_h + 15) & ~0xF;
161
// Force the offsets to be even so that chroma samples line up like we expect.
162
int pic_x = (frame_w - pic_w) / 2 & ~1;
163
int pic_y = (frame_h - pic_h) / 2 & ~1;
164
165
y = (uint8_t *)memalloc(pic_w * pic_h);
166
u = (uint8_t *)memalloc(pic_w * pic_h / 4);
167
v = (uint8_t *)memalloc(pic_w * pic_h / 4);
168
169
// We submit the buffer using the size of the picture region.
170
// libtheora will pad the picture region out to the full frame size for us,
171
// whether we pass in a full frame or not.
172
ycbcr[0].width = pic_w;
173
ycbcr[0].height = pic_h;
174
ycbcr[0].stride = pic_w;
175
ycbcr[0].data = y;
176
ycbcr[1].width = pic_w / 2;
177
ycbcr[1].height = pic_h / 2;
178
ycbcr[1].stride = pic_w / 2;
179
ycbcr[1].data = u;
180
ycbcr[2].width = pic_w / 2;
181
ycbcr[2].height = pic_h / 2;
182
ycbcr[2].stride = pic_w / 2;
183
ycbcr[2].data = v;
184
185
th_info_init(&ti);
186
ti.frame_width = frame_w;
187
ti.frame_height = frame_h;
188
ti.pic_width = pic_w;
189
ti.pic_height = pic_h;
190
ti.pic_x = pic_x;
191
ti.pic_y = pic_y;
192
ti.fps_numerator = fps;
193
ti.fps_denominator = 1;
194
ti.aspect_numerator = 1;
195
ti.aspect_denominator = 1;
196
ti.colorspace = TH_CS_UNSPECIFIED;
197
// Account for the Ogg page overhead.
198
// This is 1 byte per 255 for lacing values, plus 26 bytes per 4096 bytes for
199
// the page header, plus approximately 1/2 byte per packet (not accounted for here).
200
ti.target_bitrate = (int)(64870 * (ogg_int64_t)video_bitrate >> 16);
201
ti.quality = video_quality * 63;
202
ti.pixel_fmt = TH_PF_420;
203
td = th_encode_alloc(&ti);
204
th_info_clear(&ti);
205
ERR_FAIL_NULL_V_MSG(td, ERR_UNCONFIGURED, "Couldn't create a Theora encoder instance. Check that the video parameters are valid.");
206
207
// Setting just the granule shift only allows power-of-two keyframe spacing.
208
// Set the actual requested spacing.
209
ret = th_encode_ctl(td, TH_ENCCTL_SET_KEYFRAME_FREQUENCY_FORCE, &keyframe_frequency, sizeof(keyframe_frequency));
210
if (ret < 0) {
211
ERR_PRINT("Couldn't set keyframe interval.");
212
}
213
214
// Speed should also be set after the current encoder mode is established,
215
// since the available speed levels may change depending on the encoder mode.
216
if (speed >= 0) {
217
int speed_max;
218
ret = th_encode_ctl(td, TH_ENCCTL_GET_SPLEVEL_MAX, &speed_max, sizeof(speed_max));
219
if (ret < 0) {
220
WARN_PRINT("Couldn't determine maximum speed level.");
221
speed_max = 0;
222
}
223
ret = th_encode_ctl(td, TH_ENCCTL_SET_SPLEVEL, &speed, sizeof(speed));
224
if (ret < 0) {
225
if (ret < 0) {
226
WARN_PRINT(vformat("Couldn't set speed level to %d of %d.", speed, speed_max));
227
}
228
if (speed > speed_max) {
229
WARN_PRINT(vformat("Setting speed level to %d instead.", speed_max));
230
}
231
ret = th_encode_ctl(td, TH_ENCCTL_SET_SPLEVEL, &speed_max, sizeof(speed_max));
232
if (ret < 0) {
233
WARN_PRINT(vformat("Couldn't set speed level to %d of %d.", speed_max, speed_max));
234
}
235
}
236
}
237
238
// Write the bitstream header packets with proper page interleave.
239
th_comment_init(&tc);
240
// The first packet will get its own page automatically.
241
ogg_packet op;
242
if (th_encode_flushheader(td, &tc, &op) <= 0) {
243
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Theora library error.");
244
}
245
246
ogg_stream_packetin(&to, &op);
247
if (ogg_stream_pageout(&to, &video_page) != 1) {
248
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Ogg library error.");
249
}
250
f->store_buffer(video_page.header, video_page.header_len);
251
f->store_buffer(video_page.body, video_page.body_len);
252
253
// Create the remaining Theora headers.
254
while (true) {
255
ret = th_encode_flushheader(td, &tc, &op);
256
if (ret < 0) {
257
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Theora library error.");
258
} else if (ret == 0) {
259
break;
260
}
261
ogg_stream_packetin(&to, &op);
262
}
263
264
// Vorbis streams start with 3 standard header packets.
265
ogg_packet id;
266
ogg_packet comment;
267
ogg_packet code;
268
if (vorbis_analysis_headerout(&vd, &vc, &id, &comment, &code) < 0) {
269
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Vorbis library error.");
270
}
271
272
// ID header is automatically placed in its own page.
273
ogg_stream_packetin(&vo, &id);
274
if (ogg_stream_pageout(&vo, &audio_page) != 1) {
275
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Ogg library error.");
276
}
277
f->store_buffer(audio_page.header, audio_page.header_len);
278
f->store_buffer(audio_page.body, audio_page.body_len);
279
280
// Append remaining Vorbis header packets.
281
ogg_stream_packetin(&vo, &comment);
282
ogg_stream_packetin(&vo, &code);
283
284
// Flush the rest of our headers. This ensures the actual data in each stream will start on a new page, as per spec.
285
while (true) {
286
ret = ogg_stream_flush(&to, &video_page);
287
if (ret < 0) {
288
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Ogg library error.");
289
} else if (ret == 0) {
290
break;
291
}
292
f->store_buffer(video_page.header, video_page.header_len);
293
f->store_buffer(video_page.body, video_page.body_len);
294
}
295
296
while (true) {
297
ret = ogg_stream_flush(&vo, &audio_page);
298
if (ret < 0) {
299
ERR_FAIL_V_MSG(ERR_UNCONFIGURED, "Internal Ogg library error.");
300
} else if (ret == 0) {
301
break;
302
}
303
f->store_buffer(audio_page.header, audio_page.header_len);
304
f->store_buffer(audio_page.body, audio_page.body_len);
305
}
306
307
return OK;
308
}
309
310
// The order of the operations has been chosen so we're one frame behind writing to the stream so we can put the eos
311
// mark in the last frame.
312
// Flushing streams to the file every X frames is done to improve audio/video page interleaving thus avoiding large runs
313
// of video or audio pages.
314
Error MovieWriterOGV::write_frame(const Ref<Image> &p_image, const int32_t *p_audio_data) {
315
ERR_FAIL_COND_V(f.is_null() || td == nullptr, ERR_UNCONFIGURED);
316
317
frame_count++;
318
319
pull_audio();
320
pull_video();
321
322
if ((frame_count % 8) == 0) {
323
write_to_file();
324
}
325
326
push_audio(p_audio_data);
327
push_video(p_image);
328
329
return OK;
330
}
331
332
void MovieWriterOGV::save_page(ogg_page page) {
333
unsigned int page_size = page.header_len + page.body_len;
334
if (page_size > backup_page_size) {
335
backup_page_data = (unsigned char *)memrealloc(backup_page_data, page_size);
336
backup_page_size = page_size;
337
}
338
backup_page.header = backup_page_data;
339
backup_page.header_len = page.header_len;
340
backup_page.body = backup_page_data + page.header_len;
341
backup_page.body_len = page.body_len;
342
memcpy(backup_page.header, page.header, page.header_len);
343
memcpy(backup_page.body, page.body, page.body_len);
344
}
345
346
void MovieWriterOGV::restore_page(ogg_page *page) {
347
page->header = backup_page.header;
348
page->header_len = backup_page.header_len;
349
page->body = backup_page.body;
350
page->body_len = backup_page.body_len;
351
}
352
353
// The added complexity here is because we have to ensure pages are written in ascending timestamp order.
354
// libOgg doesn't allow checking the next page granulepos without requesting the page, and once requested it can't be
355
// returned, thus, we need to save it so that it doesn't get erased by the next `ogg_stream_packetin` call.
356
void MovieWriterOGV::write_to_file(bool p_finish) {
357
if (audio_flag) {
358
restore_page(&audio_page);
359
} else {
360
audio_flag = ogg_stream_flush(&vo, &audio_page);
361
}
362
if (video_flag) {
363
restore_page(&video_page);
364
} else {
365
video_flag = ogg_stream_flush(&to, &video_page);
366
}
367
368
bool finishing = p_finish && (audio_flag || video_flag);
369
while (finishing || (audio_flag && video_flag)) {
370
double audiotime = vorbis_granule_time(&vd, ogg_page_granulepos(&audio_page));
371
double videotime = th_granule_time(td, ogg_page_granulepos(&video_page));
372
bool video_first = audiotime >= videotime;
373
374
if (video_flag && video_first) {
375
// Flush a video page.
376
f->store_buffer(video_page.header, video_page.header_len);
377
f->store_buffer(video_page.body, video_page.body_len);
378
video_flag = ogg_stream_flush(&to, &video_page) > 0;
379
} else {
380
// Flush an audio page.
381
f->store_buffer(audio_page.header, audio_page.header_len);
382
f->store_buffer(audio_page.body, audio_page.body_len);
383
audio_flag = ogg_stream_flush(&vo, &audio_page) > 0;
384
}
385
finishing = p_finish && (audio_flag || video_flag);
386
}
387
388
if (video_flag) {
389
save_page(video_page);
390
} else if (audio_flag) {
391
save_page(audio_page);
392
}
393
}
394
395
void MovieWriterOGV::write_end() {
396
pull_audio(true);
397
pull_video(true);
398
write_to_file(true);
399
400
th_encode_free(td);
401
402
ogg_stream_clear(&vo);
403
vorbis_block_clear(&vb);
404
vorbis_dsp_clear(&vd);
405
vorbis_comment_clear(&vc);
406
vorbis_info_clear(&vi);
407
408
ogg_stream_clear(&to);
409
th_comment_clear(&tc);
410
411
memfree(y);
412
memfree(u);
413
memfree(v);
414
415
if (backup_page_data != nullptr) {
416
memfree(backup_page_data);
417
}
418
419
if (f.is_valid()) {
420
f.unref();
421
}
422
}
423
424
MovieWriterOGV::MovieWriterOGV() {
425
mix_rate = GLOBAL_GET("editor/movie_writer/mix_rate");
426
speaker_mode = AudioServer::SpeakerMode(int(GLOBAL_GET("editor/movie_writer/speaker_mode")));
427
video_quality = GLOBAL_GET("editor/movie_writer/video_quality");
428
audio_quality = GLOBAL_GET("editor/movie_writer/ogv/audio_quality");
429
speed = GLOBAL_GET("editor/movie_writer/ogv/encoding_speed");
430
keyframe_frequency = GLOBAL_GET("editor/movie_writer/ogv/keyframe_interval");
431
}
432
433