Blender V5.3
movie_write.cc
Go to the documentation of this file.
1/* SPDX-FileCopyrightText: 2006 Peter Schlaile.
2 * SPDX-FileCopyrightText: 2023-2024 Blender Authors
3 *
4 * SPDX-License-Identifier: GPL-2.0-or-later */
5
9
10#include "movie_write.hh"
11
12#include "BLI_string_ref.hh"
13
14#include "DNA_camera_types.h"
15#include "DNA_object_types.h"
16#include "DNA_scene_types.h"
17
18#include "MOV_write.hh"
19
20#include "BKE_report.hh"
21#include "BKE_scene.hh"
22
23#ifdef WITH_FFMPEG
24# include <cstdio>
25# include <cstring>
26
27# include "MEM_guardedalloc.h"
28
29# include "BLI_fileops.hh"
30# include "BLI_math_base.hh"
31# include "BLI_math_base_c.hh"
32# include "BLI_math_color_c.hh"
33# include "BLI_path_utils.hh"
34# include "BLI_string.hh"
35# include "BLI_string_utf8.hh"
36# include "BLI_utildefines.hh"
37
38# include "BKE_blender_project.hh"
39# include "BKE_image.hh"
40# include "BKE_main.hh"
41# include "BKE_path_templates.hh"
42
43# include "IMB_imbuf.hh"
44
45# include "MOV_enums.hh"
46# include "MOV_util.hh"
47
48# include "IMB_colormanagement.hh"
49
50# include "CLG_log.h"
51
52# include "ffmpeg_swscale.hh"
53# include "movie_util.hh"
54#endif
55
56namespace blender {
57
58#ifdef WITH_FFMPEG
59static CLG_LogRef LOG = {"video.write"};
60static constexpr int64_t ffmpeg_autosplit_size = 2'000'000'000;
61
62static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
63{
64 av_dict_set_int(dict, key, value, 0);
65}
66
67static void ffmpeg_movie_close(MovieWriter *context);
68static bool ffmpeg_filepath_get(MovieWriter *context,
69 char filepath[FILE_MAX],
70 const Scene *scene,
72 const RenderData *rd,
73 bool preview,
74 const char *suffix,
75 ReportList *reports);
76
77static AVFrame *alloc_frame(AVPixelFormat pix_fmt, int width, int height)
78{
79 AVFrame *f = av_frame_alloc();
80 if (f == nullptr) {
81 return nullptr;
82 }
83 const size_t align = ffmpeg_get_buffer_alignment();
84 f->format = pix_fmt;
85 f->width = width;
86 f->height = height;
87 if (av_frame_get_buffer(f, align) < 0) {
88 av_frame_free(&f);
89 return nullptr;
90 }
91 return f;
92}
93
94/* Get the correct file extensions for the requested format,
95 * first is always desired guess_format parameter */
96static const char **get_file_extensions(int format)
97{
98 switch (format) {
99 case FFMPEG_DV: {
100 static const char *rv[] = {".dv", nullptr};
101 return rv;
102 }
103 case FFMPEG_MPEG1: {
104 static const char *rv[] = {".mpg", ".mpeg", nullptr};
105 return rv;
106 }
107 case FFMPEG_MPEG2: {
108 static const char *rv[] = {".dvd", ".vob", ".mpg", ".mpeg", nullptr};
109 return rv;
110 }
111 case FFMPEG_MPEG4: {
112 static const char *rv[] = {".mp4", ".mpg", ".mpeg", nullptr};
113 return rv;
114 }
115 case FFMPEG_AVI: {
116 static const char *rv[] = {".avi", nullptr};
117 return rv;
118 }
119 case FFMPEG_MOV: {
120 static const char *rv[] = {".mov", nullptr};
121 return rv;
122 }
123 case FFMPEG_H264: {
124 /* FIXME: avi for now... */
125 static const char *rv[] = {".avi", nullptr};
126 return rv;
127 }
128
129 case FFMPEG_XVID: {
130 /* FIXME: avi for now... */
131 static const char *rv[] = {".avi", nullptr};
132 return rv;
133 }
134 case FFMPEG_FLV: {
135 static const char *rv[] = {".flv", nullptr};
136 return rv;
137 }
138 case FFMPEG_MKV: {
139 static const char *rv[] = {".mkv", nullptr};
140 return rv;
141 }
142 case FFMPEG_OGG: {
143 static const char *rv[] = {".ogv", ".ogg", nullptr};
144 return rv;
145 }
146 case FFMPEG_WEBM: {
147 static const char *rv[] = {".webm", nullptr};
148 return rv;
149 }
150 case FFMPEG_AV1: {
151 static const char *rv[] = {".mp4", ".mkv", nullptr};
152 return rv;
153 }
154 default:
155 return nullptr;
156 }
157}
158
159static void add_hdr_mastering_display_metadata(AVCodecParameters *codecpar,
160 AVCodecContext *c,
161 const ImageFormatData *imf)
162{
163 if (c->color_primaries != AVCOL_PRI_BT2020) {
164 return;
165 }
166
167 /* Get max nits from the view transform. */
168 int max_luminance = IMB_colormanagement_view_max_nits(imf->display_settings.display_device,
169 imf->view_settings.view_transform);
170 if (c->color_trc == AVCOL_TRC_ARIB_STD_B67) {
171 /* HLG is max 1000 nits, and also a good guess if not found. */
172 max_luminance = (max_luminance == 0) ? 1000 : std::min(max_luminance, 1000);
173 }
174 else if (c->color_trc == AVCOL_TRC_SMPTEST2084) {
175 /* PQ is max 10000 nits. */
176 max_luminance = std::min(max_luminance, 10000);
177 }
178
179 /* If we don't know anything, don't write metadata. The video player will make some
180 * default assumption, often 1000 nits. */
181 if (max_luminance == 0) {
182 return;
183 }
184
185 AVPacketSideData *side_data = av_packet_side_data_new(&codecpar->coded_side_data,
186 &codecpar->nb_coded_side_data,
187 AV_PKT_DATA_MASTERING_DISPLAY_METADATA,
188 sizeof(AVMasteringDisplayMetadata),
189 0);
190 if (side_data == nullptr) {
191 CLOG_ERROR(&LOG, "Failed to attached mastering display metadata to stream");
192 return;
193 }
194
195 AVMasteringDisplayMetadata *mastering_metadata = reinterpret_cast<AVMasteringDisplayMetadata *>(
196 side_data->data);
197
198 /* Rec.2020 primaries and D65 white point. */
199 mastering_metadata->has_primaries = 1;
200 mastering_metadata->display_primaries[0][0] = av_make_q(34000, 50000);
201 mastering_metadata->display_primaries[0][1] = av_make_q(16000, 50000);
202 mastering_metadata->display_primaries[1][0] = av_make_q(13250, 50000);
203 mastering_metadata->display_primaries[1][1] = av_make_q(34500, 50000);
204 mastering_metadata->display_primaries[2][0] = av_make_q(7500, 50000);
205 mastering_metadata->display_primaries[2][1] = av_make_q(3000, 50000);
206
207 mastering_metadata->white_point[0] = av_make_q(15635, 50000);
208 mastering_metadata->white_point[1] = av_make_q(16450, 50000);
209
210 mastering_metadata->has_luminance = 1;
211 mastering_metadata->min_luminance = av_make_q(1, 10000);
212 mastering_metadata->max_luminance = av_make_q(max_luminance, 1);
213}
214
221static void add_stereo3d_metadata(AVCodecParameters *codecpar,
222 const RenderData &render_data,
223 const ImageFormatData &imf)
224{
225 if (!BKE_scene_multiview_is_stereo3d(&render_data)) {
226 return;
227 }
228 if (imf.views_format != R_IMF_VIEWS_STEREO_3D) {
229 return;
230 }
231 if (imf.stereo3d_format.display_mode == S3D_DISPLAY_ANAGLYPH) {
232 return;
233 }
234 if (imf.stereo3d_format.display_mode == S3D_DISPLAY_PAGEFLIP) {
235 /* Could be supported, but requires metadata to be set for each frame. */
236 return;
237 }
238 AVPacketSideData *side_data = av_packet_side_data_new(&codecpar->coded_side_data,
239 &codecpar->nb_coded_side_data,
240 AV_PKT_DATA_STEREO3D,
241 sizeof(AVStereo3D),
242 0);
243 if (side_data == nullptr) {
244 CLOG_ERROR(&LOG, "Failed to attach stereo3d metadata to stream");
245 return;
246 }
247 AVStereo3D *stereo_3d = reinterpret_cast<AVStereo3D *>(side_data->data);
248 AVStereo3DType interlace_type = AV_STEREO3D_UNSPEC;
249 switch (imf.stereo3d_format.interlace_type) {
251 interlace_type = AV_STEREO3D_LINES;
252 break;
254 interlace_type = AV_STEREO3D_COLUMNS;
255 break;
257 interlace_type = AV_STEREO3D_CHECKERBOARD;
258 break;
259 default:
260 break;
261 }
262
263 switch (imf.stereo3d_format.display_mode) {
265 stereo_3d->type = AV_STEREO3D_SIDEBYSIDE;
266 stereo_3d->view = AV_STEREO3D_VIEW_PACKED;
267 const bool is_swapped = bool(imf.stereo3d_format.flag & S3D_SIDEBYSIDE_CROSSEYED);
268 if (is_swapped) {
269 stereo_3d->flags |= AV_STEREO3D_FLAG_INVERT;
270 }
271 break;
272 }
273
275 stereo_3d->type = AV_STEREO3D_TOPBOTTOM;
276 stereo_3d->view = AV_STEREO3D_VIEW_PACKED;
277 break;
278 }
279
281 stereo_3d->type = interlace_type;
282 stereo_3d->view = AV_STEREO3D_VIEW_PACKED;
283 const bool is_swapped = bool(imf.stereo3d_format.flag & S3D_INTERLACE_SWAP);
284 if (is_swapped) {
285 stereo_3d->flags |= AV_STEREO3D_FLAG_INVERT;
286 }
287 break;
288 }
289
293 }
294 }
295}
296
297static void add_spherical_mapping_metadata(AVCodecParameters *codecpar, const Scene &scene)
298{
299 if (scene.camera == nullptr) {
300 return;
301 }
302 if (scene.camera->type != OB_CAMERA) {
303 return;
304 }
305 const Camera &camera = *reinterpret_cast<const Camera *>(scene.camera->data);
306
307 /* Only create the side data for full equirectangular cameras. */
308 if (camera.type != CAM_PANO) {
309 return;
310 }
311 if (camera.panorama_type != CAM_PANORAMA_EQUIRECTANGULAR) {
312 return;
313 }
314 if (!compare_ff(camera.latitude_min, -M_PI_2, 1e-6) ||
315 !compare_ff(camera.latitude_max, M_PI_2, 1e-6) ||
316 !compare_ff(camera.longitude_min, -M_PI, 1e-6) ||
317 !compare_ff(camera.longitude_max, M_PI, 1e-6))
318 {
319 return;
320 }
321
322 AVPacketSideData *side_data = av_packet_side_data_new(&codecpar->coded_side_data,
323 &codecpar->nb_coded_side_data,
324 AV_PKT_DATA_SPHERICAL,
325 sizeof(AVSphericalMapping),
326 0);
327 if (side_data == nullptr) {
328 CLOG_ERROR(&LOG, "Failed to attach spherical mapping metadata to stream");
329 return;
330 }
331 AVSphericalMapping &spherical = *reinterpret_cast<AVSphericalMapping *>(side_data->data);
332 spherical.projection = AV_SPHERICAL_EQUIRECTANGULAR;
333}
334
335/* Write a frame to the output file */
336static bool write_video_frame(MovieWriter *context, AVFrame *frame, ReportList *reports)
337{
338 int ret, success = 1;
339 AVPacket *packet = av_packet_alloc();
340
341 AVCodecContext *c = context->video_codec;
342
343 frame->pts = context->video_time;
344 context->video_time++;
345
346 char error_str[AV_ERROR_MAX_STRING_SIZE];
347 ret = avcodec_send_frame(c, frame);
348 if (ret < 0) {
349 /* Can't send frame to encoder. This shouldn't happen. */
350 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
351 CLOG_ERROR(&LOG, "Can't send video frame: %s", error_str);
352 success = -1;
353 }
354
355 while (ret >= 0) {
356 ret = avcodec_receive_packet(c, packet);
357
358 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
359 /* No more packets available. */
360 break;
361 }
362 if (ret < 0) {
363 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
364 CLOG_ERROR(&LOG, "Error encoding frame: %s", error_str);
365 break;
366 }
367
368 packet->stream_index = context->video_stream->index;
369 av_packet_rescale_ts(packet, c->time_base, context->video_stream->time_base);
370# ifdef FFMPEG_USE_DURATION_WORKAROUND
371 my_guess_pkt_duration(context->outfile, context->video_stream, packet);
372# endif
373
374 if (av_interleaved_write_frame(context->outfile, packet) != 0) {
375 success = -1;
376 break;
377 }
378 }
379
380 if (!success) {
381 BKE_report(reports, RPT_ERROR, "Error writing frame");
382 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
383 CLOG_INFO(&LOG, "ffmpeg: error writing video frame: %s", error_str);
384 }
385
386 av_packet_free(&packet);
387
388 return success;
389}
390
391/* Allocate new ImBuf of the size of the given input which only contains float buffer with pixels
392 * from the input.
393 *
394 * For the float image buffers it is similar to IMB_dupImBuf() but it ensures that the byte buffer
395 * is not allocated.
396 *
397 * For the byte image buffers it is similar to IMB_dupImBuf() followed by IMB_float_from_byte(),
398 * but without temporary allocation, and result containing only single float buffer.
399 *
400 * No color space conversion is performed. The result float buffer might be in a non-linear space
401 * denoted by the float_buffer.colorspace. */
402static ImBuf *alloc_imbuf_for_colorspace_transform(const ImBuf *input_ibuf)
403{
404 if (!input_ibuf) {
405 return nullptr;
406 }
407
408 /* Allocate new image buffer without float buffer just yet.
409 * This allows to properly initialize the number of channels used in the buffer. */
410 /* TODO(sergey): Make it a reusable function.
411 * This is a common pattern used in few areas with the goal to bypass the hardcoded number of
412 * channels used by IMB_allocImBuf(). */
413 ImBuf *result_ibuf = IMB_allocImBuf(input_ibuf->x, input_ibuf->y, ImBufFlags::Zero);
414 result_ibuf->color_mode = input_ibuf->color_mode;
415 result_ibuf->channels = input_ibuf->float_data() ? input_ibuf->channels : 4;
416
417 /* Transfer flags related to color space conversion from the original image buffer. */
418 result_ibuf->flags |= (input_ibuf->flags & ImBufFlags::AlphaChannelPacked);
419
420 if (input_ibuf->float_data()) {
421 /* Simple case: copy pixels from the source image as-is, without any conversion.
422 * The result has the same colorspace as the input. */
423 result_ibuf->float_buffer = input_ibuf->float_buffer;
424 }
425 else {
426 /* Convert byte buffer to float buffer. */
427 /* Allocate float buffer with the proper number of channels. */
428 const size_t num_pixels = IMB_get_pixel_count(input_ibuf);
429 float *buffer = MEM_new_array_uninitialized<float>(num_pixels * result_ibuf->channels,
430 "movie hdr image");
431 result_ibuf->assign_float_data(buffer);
432 IMB_buffer_float_from_byte(result_ibuf->float_data_for_write(),
433 input_ibuf->byte_data(),
434 input_ibuf->x,
435 input_ibuf->y,
436 result_ibuf->x,
437 input_ibuf->x);
438 }
439
440 return result_ibuf;
441}
442
443/* read and encode a frame of video from the buffer */
444static AVFrame *generate_video_frame(MovieWriter *context, const ImBuf *input_ibuf)
445{
446 /* Use float input if needed. */
447 const bool use_float =
448 context->img_convert_frame != nullptr &&
449 !(context->img_convert_frame->format == AV_PIX_FMT_RGBA &&
450 ELEM(context->img_convert_frame->colorspace, AVCOL_SPC_RGB, AVCOL_SPC_UNSPECIFIED));
451
452 const ImBuf *image = (use_float && input_ibuf->float_data() == nullptr) ?
453 alloc_imbuf_for_colorspace_transform(input_ibuf) :
454 input_ibuf;
455
456 const uint8_t *pixels = image->byte_data();
457 const float *pixels_fl = image->float_data();
458
459 if ((!use_float && (pixels == nullptr)) || (use_float && (pixels_fl == nullptr))) {
460 if (image != input_ibuf) {
461 IMB_freeImBuf(const_cast<ImBuf *>(image));
462 }
463 return nullptr;
464 }
465
466 AVCodecParameters *codec = context->video_stream->codecpar;
467 int height = codec->height;
468 AVFrame *rgb_frame;
469
470 if (context->img_convert_frame != nullptr) {
471 /* Pixel format conversion is needed. */
472 rgb_frame = context->img_convert_frame;
473 }
474 else {
475 /* The output pixel format is Blender's internal pixel format. */
476 rgb_frame = context->current_frame;
477 }
478
479 /* Ensure frame is writable. Some video codecs might have made previous frame
480 * shared (i.e. not writable). */
481 av_frame_make_writable(rgb_frame);
482
483 const size_t linesize_dst = rgb_frame->linesize[0];
484 if (use_float) {
485 /* Float image: need to split up the image into a planar format,
486 * because `libswscale` does not support RGBA->YUV conversions from
487 * packed float formats.
488 * Un-premultiply the image if the output format supports alpha, to
489 * match the format of the byte image. */
490 BLI_assert_msg(rgb_frame->linesize[1] == linesize_dst &&
491 rgb_frame->linesize[2] == linesize_dst &&
492 rgb_frame->linesize[3] == linesize_dst,
493 "ffmpeg frame should be 4 same size planes for a floating point image case");
494 for (int y = 0; y < height; y++) {
495 size_t dst_offset = linesize_dst * (height - y - 1);
496 float *dst_g = reinterpret_cast<float *>(rgb_frame->data[0] + dst_offset);
497 float *dst_b = reinterpret_cast<float *>(rgb_frame->data[1] + dst_offset);
498 float *dst_r = reinterpret_cast<float *>(rgb_frame->data[2] + dst_offset);
499 float *dst_a = reinterpret_cast<float *>(rgb_frame->data[3] + dst_offset);
500 const float *src = pixels_fl + image->x * y * 4;
501
502 if (MOV_codec_supports_alpha(context->ffmpeg_codec, context->ffmpeg_profile)) {
503 for (int x = 0; x < image->x; x++) {
504 float tmp[4];
505 premul_to_straight_v4_v4(tmp, src);
506 *dst_r++ = tmp[0];
507 *dst_g++ = tmp[1];
508 *dst_b++ = tmp[2];
509 *dst_a++ = tmp[3];
510 src += 4;
511 }
512 }
513 else {
514 for (int x = 0; x < image->x; x++) {
515 *dst_r++ = src[0];
516 *dst_g++ = src[1];
517 *dst_b++ = src[2];
518 *dst_a++ = src[3];
519 src += 4;
520 }
521 }
522 }
523 }
524 else {
525 /* Byte image: flip the image vertically. */
526 const size_t linesize_src = rgb_frame->width * 4;
527 for (int y = 0; y < height; y++) {
528 uint8_t *target = rgb_frame->data[0] + linesize_dst * (height - y - 1);
529 const uint8_t *src = pixels + linesize_src * y;
530
531 /* NOTE: this is endianness-sensitive. */
532 /* The target buffer is always expected to contain little-endian RGBA values. */
533 memcpy(target, src, linesize_src);
534 }
535 }
536
537 /* Convert to the output pixel format, if it's different that Blender's internal one. */
538 if (context->img_convert_frame != nullptr) {
539 BLI_assert(context->sws_ctx != nullptr);
540 /* Ensure the frame we are scaling to is writable as well. */
541 av_frame_make_writable(context->current_frame);
542 ffmpeg_sws_scale_frame(context->sws_ctx, context->current_frame, rgb_frame);
543 }
544
545 if (image != input_ibuf) {
546 IMB_freeImBuf(const_cast<ImBuf *>(image));
547 }
548
549 return context->current_frame;
550}
551
552static AVRational calc_time_base(uint den, double num, AVCodecID codec_id)
553{
554 /* Convert the input 'num' to an integer. Simply shift the decimal places until we get an integer
555 * (within a floating point error range).
556 * For example if we have `den = 3` and `num = 0.1` then the fps is: `den/num = 30` fps.
557 * When converting this to a FFMPEG time base, we want num to be an integer.
558 * So we simply move the decimal places of both numbers. i.e. `den = 30`, `num = 1`. */
559 float eps = FLT_EPSILON;
560 const uint DENUM_MAX = (codec_id == AV_CODEC_ID_MPEG4) ? (1UL << 16) - 1 : (1UL << 31) - 1;
561
562 /* Calculate the precision of the initial floating point number. */
563 if (num > 1.0) {
564 const uint num_integer_bits = log2_floor_u(uint(num));
565
566 /* Formula for calculating the epsilon value: (power of two range) / (pow mantissa bits)
567 * For example, a float has 23 mantissa bits and the float value 3.5f as a pow2 range of
568 * (4-2=2):
569 * (2) / pow2(23) = floating point precision for 3.5f
570 */
571 eps = float(1 << num_integer_bits) * FLT_EPSILON;
572 }
573
574 /* Calculate how many decimal shifts we can do until we run out of precision. */
575 const int max_num_shift = fabsf(log10f(eps));
576 /* Calculate how many times we can shift the denominator. */
577 const int max_den_shift = log10f(DENUM_MAX) - log10f(den);
578 const int max_iter = min_ii(max_num_shift, max_den_shift);
579
580 for (int i = 0; i < max_iter && fabs(num - round(num)) > eps; i++) {
581 /* Increase the number and denominator until both are integers. */
582 num *= 10;
583 den *= 10;
584 eps *= 10;
585 }
586
587 AVRational time_base;
588 time_base.den = den;
589 time_base.num = int(num);
590
591 return time_base;
592}
593
594static const AVCodec *get_av1_encoder(
595 MovieWriter *context, const RenderData *rd, AVDictionary **opts, int rectx, int recty)
596{
597 /* There are three possible encoders for AV1: `libaom-av1`, librav1e, and `libsvtav1`. librav1e
598 * tends to give the best compression quality while `libsvtav1` tends to be the fastest encoder.
599 * One of each will be picked based on the preset setting, and if a particular encoder is not
600 * available, then use the default returned by FFMpeg. */
601 const AVCodec *codec = nullptr;
602 switch (context->ffmpeg_preset) {
603 case FFM_PRESET_BEST:
604 /* `libaom-av1` may produce better VMAF-scoring videos in several cases, but there are cases
605 * where using a different encoder is desirable, such as in #103849. */
606 codec = avcodec_find_encoder_by_name("librav1e");
607 if (!codec) {
608 /* Fall back to `libaom-av1` if librav1e is not found. */
609 codec = avcodec_find_encoder_by_name("libaom-av1");
610 }
611 break;
613 codec = avcodec_find_encoder_by_name("libsvtav1");
614 break;
615 case FFM_PRESET_GOOD:
616 default:
617 codec = avcodec_find_encoder_by_name("libaom-av1");
618 break;
619 }
620
621 /* Use the default AV1 encoder if the specified encoder wasn't found. */
622 if (!codec) {
623 codec = avcodec_find_encoder(AV_CODEC_ID_AV1);
624 }
625
626 /* Apply AV1 encoder specific settings. */
627 if (codec) {
628 if (STREQ(codec->name, "librav1e")) {
629 /* Set "tiles" to 8 to enable multi-threaded encoding. */
630 if (rd->threads > 8) {
631 ffmpeg_dict_set_int(opts, "tiles", rd->threads);
632 }
633 else {
634 ffmpeg_dict_set_int(opts, "tiles", 8);
635 }
636
637 /* Use a reasonable speed setting based on preset. Speed ranges from 0-10.
638 * Must check context->ffmpeg_preset again in case this encoder was selected due to the
639 * absence of another. */
640 switch (context->ffmpeg_preset) {
641 case FFM_PRESET_BEST:
642 ffmpeg_dict_set_int(opts, "speed", 4);
643 break;
645 ffmpeg_dict_set_int(opts, "speed", 10);
646 break;
647 case FFM_PRESET_GOOD:
648 default:
649 ffmpeg_dict_set_int(opts, "speed", 6);
650 break;
651 }
652 /* Set gop_size as rav1e's "--keyint". */
653 char buffer[64];
654 SNPRINTF_UTF8(buffer, "keyint=%d", context->ffmpeg_gop_size);
655 av_dict_set(opts, "rav1e-params", buffer, 0);
656 }
657 else if (STREQ(codec->name, "libsvtav1")) {
658 /* Set preset value based on ffmpeg_preset.
659 * Must check `context->ffmpeg_preset` again in case this encoder was selected due to the
660 * absence of another. */
661 switch (context->ffmpeg_preset) {
663 ffmpeg_dict_set_int(opts, "preset", 8);
664 break;
665 case FFM_PRESET_BEST:
666 ffmpeg_dict_set_int(opts, "preset", 3);
667 break;
668 case FFM_PRESET_GOOD:
669 default:
670 ffmpeg_dict_set_int(opts, "preset", 5);
671 break;
672 }
673 }
674 else if (STREQ(codec->name, "libaom-av1")) {
675 /* Speed up libaom-av1 encoding by enabling multi-threading and setting tiles. */
676 ffmpeg_dict_set_int(opts, "row-mt", 1);
677 const char *tiles_string = nullptr;
678 bool tiles_string_is_dynamic = false;
679 if (rd->threads > 0) {
680 /* See if threads is a square. */
681 int threads_sqrt = sqrtf(rd->threads);
682 if (threads_sqrt < 4) {
683 /* Ensure a default minimum. */
684 threads_sqrt = 4;
685 }
686 if (is_power_of_2_i(threads_sqrt) && threads_sqrt * threads_sqrt == rd->threads) {
687 /* Is a square num, therefore just do "sqrt x sqrt" for tiles parameter. */
688 int digits = 0;
689 for (int t_sqrt_copy = threads_sqrt; t_sqrt_copy > 0; t_sqrt_copy /= 10) {
690 ++digits;
691 }
692 /* A char array need only an alignment of 1. */
693 char *tiles_string_mut = (char *)calloc(digits * 2 + 2, 1);
694 BLI_snprintf_utf8(tiles_string_mut, digits * 2 + 2, "%dx%d", threads_sqrt, threads_sqrt);
695 tiles_string_is_dynamic = true;
696 tiles_string = tiles_string_mut;
697 }
698 else {
699 /* Is not a square num, set greater side based on longer side, or use a square if both
700 * sides are equal. */
701 int sqrt_p2 = power_of_2_min_i(threads_sqrt);
702 if (sqrt_p2 < 2) {
703 /* Ensure a default minimum. */
704 sqrt_p2 = 2;
705 }
706 int sqrt_p2_next = power_of_2_min_i(int(rd->threads) / sqrt_p2);
707 if (sqrt_p2_next < 1) {
708 sqrt_p2_next = 1;
709 }
710 if (sqrt_p2 > sqrt_p2_next) {
711 /* Ensure sqrt_p2_next is greater or equal to sqrt_p2. */
712 int temp = sqrt_p2;
713 sqrt_p2 = sqrt_p2_next;
714 sqrt_p2_next = temp;
715 }
716 int combined_digits = 0;
717 for (int sqrt_p2_copy = sqrt_p2; sqrt_p2_copy > 0; sqrt_p2_copy /= 10) {
718 ++combined_digits;
719 }
720 for (int sqrt_p2_copy = sqrt_p2_next; sqrt_p2_copy > 0; sqrt_p2_copy /= 10) {
721 ++combined_digits;
722 }
723 /* A char array need only an alignment of 1. */
724 char *tiles_string_mut = (char *)calloc(combined_digits + 2, 1);
725 if (rectx > recty) {
727 tiles_string_mut, combined_digits + 2, "%dx%d", sqrt_p2_next, sqrt_p2);
728 }
729 else if (rectx < recty) {
731 tiles_string_mut, combined_digits + 2, "%dx%d", sqrt_p2, sqrt_p2_next);
732 }
733 else {
734 BLI_snprintf_utf8(tiles_string_mut, combined_digits + 2, "%dx%d", sqrt_p2, sqrt_p2);
735 }
736 tiles_string_is_dynamic = true;
737 tiles_string = tiles_string_mut;
738 }
739 }
740 else {
741 /* Thread count unknown, default to 8. */
742 if (rectx > recty) {
743 tiles_string = "4x2";
744 }
745 else if (rectx < recty) {
746 tiles_string = "2x4";
747 }
748 else {
749 tiles_string = "2x2";
750 }
751 }
752 av_dict_set(opts, "tiles", tiles_string, 0);
753 if (tiles_string_is_dynamic) {
754 free((void *)tiles_string);
755 }
756 /* libaom-av1 uses "cpu-used" instead of "preset" for defining compression quality.
757 * This value is in a range from 0-8. 0 and 8 are extremes, but we will allow 8.
758 * Must check context->ffmpeg_preset again in case this encoder was selected due to the
759 * absence of another. */
760 switch (context->ffmpeg_preset) {
762 ffmpeg_dict_set_int(opts, "cpu-used", 8);
763 break;
764 case FFM_PRESET_BEST:
765 ffmpeg_dict_set_int(opts, "cpu-used", 4);
766 break;
767 case FFM_PRESET_GOOD:
768 default:
769 ffmpeg_dict_set_int(opts, "cpu-used", 6);
770 break;
771 }
772 }
773 }
774
775 return codec;
776}
777
778/* Remap H.264 CRF to H.265 CRF: 17..32 range (23 default) to 20..37 range (28 default).
779 * https://trac.ffmpeg.org/wiki/Encode/H.265 */
780static int remap_crf_to_h265_crf(int crf, bool is_10_or_12_bpp)
781{
782 /* 10/12 bit videos seem to need slightly lower CRF value for similar quality. */
783 const int bias = is_10_or_12_bpp ? -3 : 0;
784 switch (crf) {
786 return 20 + bias;
787 case FFM_CRF_HIGH:
788 return 24 + bias;
789 case FFM_CRF_MEDIUM:
790 return 28 + bias;
791 case FFM_CRF_LOW:
792 return 31 + bias;
793 case FFM_CRF_VERYLOW:
794 return 34 + bias;
795 case FFM_CRF_LOWEST:
796 return 37 + bias;
797 }
798 return crf;
799}
800
801static const AVCodec *get_prores_encoder(const ImageFormatData *imf, int rectx, int recty)
802{
803 /* The prores_aw encoder currently (April 2025) has issues when encoding alpha with high
804 * resolution but is faster in most cases for similar quality. Use it instead of prores_ks
805 * if possible. (Upstream issue https://trac.ffmpeg.org/ticket/11536) */
806 if (imf->color_mode == ImColorMode::RGBA) {
807 if ((size_t(rectx) * size_t(recty)) > (3840 * 2160)) {
808 return avcodec_find_encoder_by_name("prores_ks");
809 }
810 }
811 return avcodec_find_encoder_by_name("prores_aw");
812}
813
814/* 10bpp H264: remap 0..51 range to -12..51 range
815 * https://trac.ffmpeg.org/wiki/Encode/H.264#a1.ChooseaCRFvalue */
816static int remap_crf_to_h264_10bpp_crf(int crf)
817{
818 crf = int(-12.0f + (crf / 51.0f) * 63.0f);
819 crf = max_ii(crf, 0);
820 return crf;
821}
822
823static void set_quality_rate_options(const MovieWriter *context,
824 const AVCodecID codec_id,
825 const FFMpegCodecData *ffcodecdata,
826 const ImageFormatData *imf,
827 AVDictionary **opts)
828{
829 AVCodecContext *c = context->video_codec;
830
831 /* Handle constant bit rate (CBR) case. */
832 if (!MOV_codec_supports_crf(codec_id) || context->ffmpeg_crf < 0) {
833 c->bit_rate = context->ffmpeg_video_bitrate * 1000;
834 c->rc_max_rate = ffcodecdata->rc_max_rate * 1000;
835 c->rc_min_rate = ffcodecdata->rc_min_rate * 1000;
836 c->rc_buffer_size = ffcodecdata->rc_buffer_size * 1024;
837 return;
838 }
839
840 /* For VP9 bit rate must be set to zero to get CRF mode, just set it to zero for all codecs:
841 * https://trac.ffmpeg.org/wiki/Encode/VP9 */
842 c->bit_rate = 0;
843
844 const bool is_10_bpp = imf->depth == R_IMF_CHAN_DEPTH_10;
845 const bool is_12_bpp = imf->depth == R_IMF_CHAN_DEPTH_12;
846 const bool av1_librav1e = codec_id == AV_CODEC_ID_AV1 && STREQ(c->codec->name, "librav1e");
847 const bool av1_libsvtav1 = codec_id == AV_CODEC_ID_AV1 && STREQ(c->codec->name, "libsvtav1");
848
849 /* Handle "lossless" case. */
850 if (context->ffmpeg_crf == FFM_CRF_LOSSLESS) {
851 if (codec_id == AV_CODEC_ID_VP9) {
852 /* VP9 needs "lossless": https://trac.ffmpeg.org/wiki/Encode/VP9#LosslessVP9 */
853 ffmpeg_dict_set_int(opts, "lossless", 1);
854 }
855 else if (codec_id == AV_CODEC_ID_H264 && is_10_bpp) {
856 /* 10bpp H264 needs "qp": https://trac.ffmpeg.org/wiki/Encode/H.264#a1.ChooseaCRFvalue */
857 ffmpeg_dict_set_int(opts, "qp", 0);
858 }
859 else if (codec_id == AV_CODEC_ID_H265) {
860 /* H.265 needs "lossless" in private params; also make it much less verbose. */
861 av_dict_set(opts, "x265-params", "log-level=1:lossless=1", 0);
862 }
863 else if (codec_id == AV_CODEC_ID_AV1 && (av1_librav1e || av1_libsvtav1)) {
864 /* AV1 in some encoders needs qp=0 for lossless. */
865 ffmpeg_dict_set_int(opts, "qp", 0);
866 }
867 else {
868 /* For others crf=0 means lossless. */
869 ffmpeg_dict_set_int(opts, "crf", 0);
870 }
871 return;
872 }
873
874 /* Handle CRF setting cases. */
875 int crf = context->ffmpeg_crf;
876
877 if (codec_id == AV_CODEC_ID_H264 && is_10_bpp) {
878 crf = remap_crf_to_h264_10bpp_crf(crf);
879 }
880 else if (codec_id == AV_CODEC_ID_H265) {
881 if (!context->custom_crf) {
882 crf = remap_crf_to_h265_crf(crf, is_10_bpp || is_12_bpp);
883 }
884 /* Make H.265 much less verbose. */
885 av_dict_set(opts, "x265-params", "log-level=1", 0);
886 }
887
888 if (av1_librav1e) {
889 /* Remap crf 0..51 to qp 0..255 for AV1 librav1e. */
890 int qp = int(float(crf) / 51.0f * 255.0f);
891 qp = clamp_i(qp, 0, 255);
892 ffmpeg_dict_set_int(opts, "qp", qp);
893 }
894 else if (av1_libsvtav1) {
895 /* libsvtav1 used to take CRF as "qp" parameter, do that. */
896 ffmpeg_dict_set_int(opts, "qp", crf);
897 }
898 else {
899 ffmpeg_dict_set_int(opts, "crf", crf);
900 }
901}
902
903static void set_colorspace_options(AVCodecContext *c, const ColorSpace *colorspace)
904{
905 const AVPixFmtDescriptor *pix_fmt_desc = av_pix_fmt_desc_get(c->pix_fmt);
906 const bool is_rgb_format = (pix_fmt_desc->flags & AV_PIX_FMT_FLAG_RGB);
907 const bool rgb_matrix = false;
908
909 int cicp[4];
911 colorspace, ColorManagedFileOutput::Video, rgb_matrix, cicp))
912 {
913 /* Note ffmpeg enums are documented to match CICP. */
914 c->color_primaries = AVColorPrimaries(cicp[0]);
915 c->color_trc = AVColorTransferCharacteristic(cicp[1]);
916 c->colorspace = (is_rgb_format) ? AVCOL_SPC_RGB : AVColorSpace(cicp[2]);
917 /* CICP 1 means full range, FFmpeg enum is the other way around. */
918 c->color_range = (is_rgb_format || cicp[3] == 1) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG;
919 }
920 else if (!is_rgb_format) {
921 /* Most colorspaces will have valid CICP values from the above but if not
922 * set to unspecified (which most players treat as sRGB) */
923 c->color_primaries = AVCOL_PRI_UNSPECIFIED;
924 c->color_trc = AVCOL_TRC_UNSPECIFIED;
925 c->colorspace = AVCOL_SPC_BT709;
926 /* TODO(sergey): Consider making the range an option to cover more use-cases. */
927 c->color_range = AVCOL_RANGE_MPEG;
928 }
929 else {
930 /* We don't set anything for pure sRGB writing, for backwards compatibility. */
931 }
932}
933
934static AVStream *alloc_video_stream(MovieWriter *context,
935 const Scene &scene,
936 const ImageFormatData *imf,
937 AVCodecID codec_id,
938 AVFormatContext *of,
939 int rectx,
940 int recty,
941 char *error,
942 int error_maxncpy)
943{
944 AVStream *st;
945 const AVCodec *codec;
946 AVDictionary *opts = nullptr;
947 const RenderData *rd = &scene.r;
948
949 error[0] = '\0';
950
951 st = avformat_new_stream(of, nullptr);
952 if (!st) {
953 return nullptr;
954 }
955 st->id = 0;
956
957 /* Set up the codec context */
958
959 if (codec_id == AV_CODEC_ID_AV1) {
960 /* Use get_av1_encoder() to get the ideal (hopefully) encoder for AV1 based
961 * on given parameters, and also set up opts. */
962 codec = get_av1_encoder(context, rd, &opts, rectx, recty);
963 }
964 else if (codec_id == AV_CODEC_ID_PRORES) {
965 codec = get_prores_encoder(imf, rectx, recty);
966 }
967 else {
968 codec = avcodec_find_encoder(codec_id);
969 }
970 if (!codec) {
971 CLOG_ERROR(&LOG, "Couldn't find valid video codec");
972 context->video_codec = nullptr;
973 return nullptr;
974 }
975
976 context->video_codec = avcodec_alloc_context3(codec);
977 AVCodecContext *c = context->video_codec;
978
979 /* Get some values from the current render settings */
980
981 c->width = rectx;
982 c->height = recty;
983
984 if (context->ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
985 /* FIXME: Really bad hack (tm) for NTSC support */
986 c->time_base.den = 2997;
987 c->time_base.num = 100;
988 }
989 else if (float(int(rd->frs_sec_base)) == rd->frs_sec_base) {
990 c->time_base.den = rd->frs_sec;
991 c->time_base.num = int(rd->frs_sec_base);
992 }
993 else {
994 c->time_base = calc_time_base(rd->frs_sec, rd->frs_sec_base, codec_id);
995 }
996
997 /* As per the time-base documentation here:
998 * https://www.ffmpeg.org/ffmpeg-codecs.html#Codec-Options
999 * We want to set the time base to (1 / fps) for fixed frame rate video.
1000 * If it is not possible, we want to set the time-base numbers to something as
1001 * small as possible.
1002 */
1003 if (c->time_base.num != 1) {
1004 AVRational new_time_base;
1005 if (av_reduce(
1006 &new_time_base.num, &new_time_base.den, c->time_base.num, c->time_base.den, INT_MAX))
1007 {
1008 /* Exact reduction was possible. Use the new value. */
1009 c->time_base = new_time_base;
1010 }
1011 }
1012
1013 st->time_base = c->time_base;
1014
1015 c->gop_size = context->ffmpeg_gop_size;
1016 c->max_b_frames = context->ffmpeg_max_b_frames;
1017
1018 set_quality_rate_options(context, codec_id, &rd->ffcodecdata, imf, &opts);
1019
1020 if (context->ffmpeg_preset) {
1021 /* 'preset' is used by h.264, 'deadline' is used by WEBM/VP9. I'm not
1022 * setting those properties conditionally based on the video codec,
1023 * as the FFmpeg encoder simply ignores unknown settings anyway. */
1024 char const *preset_name = nullptr; /* Used by h.264. */
1025 char const *deadline_name = nullptr; /* Used by WEBM/VP9. */
1026 switch (context->ffmpeg_preset) {
1027 case FFM_PRESET_GOOD:
1028 preset_name = "medium";
1029 deadline_name = "good";
1030 break;
1031 case FFM_PRESET_BEST:
1032 preset_name = "slower";
1033 deadline_name = "best";
1034 break;
1036 preset_name = "superfast";
1037 deadline_name = "realtime";
1038 break;
1039 default:
1040 CLOG_WARN(&LOG, "Unknown preset number %i, ignoring.", context->ffmpeg_preset);
1041 }
1042 /* "codec_id != AV_CODEC_ID_AV1" is required due to "preset" already being set by an AV1 codec.
1043 */
1044 if (preset_name != nullptr && codec_id != AV_CODEC_ID_AV1) {
1045 av_dict_set(&opts, "preset", preset_name, 0);
1046 }
1047 if (deadline_name != nullptr) {
1048 av_dict_set(&opts, "deadline", deadline_name, 0);
1049 }
1050 }
1051
1052 /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
1053
1054 const enum AVPixelFormat *pix_fmts = ffmpeg_get_pix_fmts(c, codec);
1055 if (pix_fmts) {
1056 c->pix_fmt = pix_fmts[0];
1057 }
1058 else {
1059 /* makes HuffYUV happy ... */
1060 c->pix_fmt = AV_PIX_FMT_YUV422P;
1061 }
1062
1063 const bool is_10_bpp = imf->depth == R_IMF_CHAN_DEPTH_10;
1064 const bool is_12_bpp = imf->depth == R_IMF_CHAN_DEPTH_12;
1065 const bool is_16_bpp = imf->depth == R_IMF_CHAN_DEPTH_16;
1066
1067 if (is_10_bpp) {
1068 c->pix_fmt = AV_PIX_FMT_YUV420P10LE;
1069 }
1070 else if (is_12_bpp) {
1071 c->pix_fmt = AV_PIX_FMT_YUV420P12LE;
1072 }
1073
1074 if (context->ffmpeg_type == FFMPEG_XVID) {
1075 /* Alas! */
1076 c->pix_fmt = AV_PIX_FMT_YUV420P;
1077 c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
1078 }
1079
1080 if (codec_id == AV_CODEC_ID_H265) {
1081 /* H.265 needs hvc1 tag for Apple compatibility, see
1082 * https://trac.ffmpeg.org/wiki/Encode/H.265#FinalCutandApplestuffcompatibility
1083 * Note that in case we are doing H.265 into an XviD container,
1084 * this overwrites the tag set above. But that should not be what anyone does. */
1085 c->codec_tag = MKTAG('h', 'v', 'c', '1');
1086 }
1087
1088 /* Keep lossless encodes in the RGB domain. */
1089 if (codec_id == AV_CODEC_ID_HUFFYUV) {
1090 if (imf->color_mode == ImColorMode::RGBA) {
1091 c->pix_fmt = AV_PIX_FMT_BGRA;
1092 }
1093 else {
1094 c->pix_fmt = AV_PIX_FMT_RGB32;
1095 }
1096 }
1097
1098 if (codec_id == AV_CODEC_ID_DNXHD) {
1099 if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT) {
1100 /* Set the block decision algorithm to be of the highest quality ("rd" == 2). */
1101 c->mb_decision = 2;
1102 }
1103 }
1104
1105 if (codec_id == AV_CODEC_ID_FFV1) {
1106 if (imf->color_mode == ImColorMode::BW) {
1107 c->pix_fmt = AV_PIX_FMT_GRAY8;
1108 if (is_10_bpp) {
1109 c->pix_fmt = AV_PIX_FMT_GRAY10;
1110 }
1111 else if (is_12_bpp) {
1112 c->pix_fmt = AV_PIX_FMT_GRAY12;
1113 }
1114 else if (is_16_bpp) {
1115 c->pix_fmt = AV_PIX_FMT_GRAY16;
1116 }
1117 }
1118 else if (imf->color_mode == ImColorMode::RGBA) {
1119 c->pix_fmt = AV_PIX_FMT_RGB32;
1120 if (is_10_bpp) {
1121 c->pix_fmt = AV_PIX_FMT_GBRAP10;
1122 }
1123 else if (is_12_bpp) {
1124 c->pix_fmt = AV_PIX_FMT_GBRAP12;
1125 }
1126 else if (is_16_bpp) {
1127 c->pix_fmt = AV_PIX_FMT_GBRAP16;
1128 }
1129 }
1130 else { /* RGB */
1131 c->pix_fmt = AV_PIX_FMT_0RGB32;
1132 if (is_10_bpp) {
1133 c->pix_fmt = AV_PIX_FMT_GBRP10;
1134 }
1135 else if (is_12_bpp) {
1136 c->pix_fmt = AV_PIX_FMT_GBRP12;
1137 }
1138 else if (is_16_bpp) {
1139 c->pix_fmt = AV_PIX_FMT_GBRP16;
1140 }
1141 }
1142 }
1143
1144 if (codec_id == AV_CODEC_ID_QTRLE) {
1145 if (imf->color_mode == ImColorMode::BW) {
1146 c->pix_fmt = AV_PIX_FMT_GRAY8;
1147 }
1148 else if (imf->color_mode == ImColorMode::RGBA) {
1149 c->pix_fmt = AV_PIX_FMT_ARGB;
1150 }
1151 else { /* RGB */
1152 c->pix_fmt = AV_PIX_FMT_RGB24;
1153 }
1154 }
1155
1156 if (codec_id == AV_CODEC_ID_VP9 && imf->color_mode == ImColorMode::RGBA) {
1157 c->pix_fmt = AV_PIX_FMT_YUVA420P;
1158 }
1159 else if (ELEM(codec_id, AV_CODEC_ID_H264, AV_CODEC_ID_H265, AV_CODEC_ID_VP9, AV_CODEC_ID_AV1) &&
1160 (context->ffmpeg_crf == 0))
1161 {
1162 /* Use 4:4:4 instead of 4:2:0 pixel format for lossless rendering. */
1163 c->pix_fmt = AV_PIX_FMT_YUV444P;
1164 if (is_10_bpp) {
1165 c->pix_fmt = AV_PIX_FMT_YUV444P10LE;
1166 }
1167 else if (is_12_bpp) {
1168 c->pix_fmt = AV_PIX_FMT_YUV444P12LE;
1169 }
1170 }
1171
1172 if (codec_id == AV_CODEC_ID_PNG) {
1173 if (imf->color_mode == ImColorMode::BW) {
1174 c->pix_fmt = AV_PIX_FMT_GRAY8;
1175 }
1176 else if (imf->color_mode == ImColorMode::RGBA) {
1177 c->pix_fmt = AV_PIX_FMT_RGBA;
1178 }
1179 else { /* RGB */
1180 c->pix_fmt = AV_PIX_FMT_RGB24;
1181 }
1182 }
1183 if (codec_id == AV_CODEC_ID_PRORES) {
1184 if ((context->ffmpeg_profile >= FFM_PRORES_PROFILE_422_PROXY) &&
1185 (context->ffmpeg_profile <= FFM_PRORES_PROFILE_422_HQ))
1186 {
1187 c->profile = context->ffmpeg_profile;
1188 c->pix_fmt = AV_PIX_FMT_YUV422P10LE;
1189 }
1190 else if ((context->ffmpeg_profile >= FFM_PRORES_PROFILE_4444) &&
1191 (context->ffmpeg_profile <= FFM_PRORES_PROFILE_4444_XQ))
1192 {
1193 c->profile = context->ffmpeg_profile;
1194 c->pix_fmt = AV_PIX_FMT_YUV444P10LE;
1195
1196 if (imf->color_mode == ImColorMode::RGBA) {
1197 c->pix_fmt = AV_PIX_FMT_YUVA444P10LE;
1198 }
1199 }
1200 else {
1201 CLOG_ERROR(&LOG, "ffmpeg: invalid profile %d", context->ffmpeg_profile);
1202 }
1203 }
1204
1205 if (of->oformat->flags & AVFMT_GLOBALHEADER) {
1206 CLOG_STR_INFO(&LOG, "ffmpeg: using global video header");
1207 c->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
1208 }
1209
1210 /* Set colorspace based on display space of image. */
1211 const ColorSpace *display_colorspace = IMB_colormangement_display_get_color_space(
1212 &imf->view_settings, &imf->display_settings);
1213 set_colorspace_options(c, display_colorspace);
1214
1215 /* xasp & yasp got float lately... */
1216
1217 st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q((double(rd->xasp) / double(rd->yasp)),
1218 255);
1219 st->avg_frame_rate = av_inv_q(c->time_base);
1220
1221 if (codec->capabilities & AV_CODEC_CAP_OTHER_THREADS) {
1222 c->thread_count = 0;
1223 }
1224 else {
1225 c->thread_count = MOV_thread_count();
1226 }
1227
1228 if (codec->capabilities & AV_CODEC_CAP_FRAME_THREADS) {
1229 c->thread_type = FF_THREAD_FRAME;
1230 }
1231 else if (codec->capabilities & AV_CODEC_CAP_SLICE_THREADS) {
1232 c->thread_type = FF_THREAD_SLICE;
1233 }
1234
1235 int ret = avcodec_open2(c, codec, &opts);
1236
1237 if (ret < 0) {
1238 char error_str[AV_ERROR_MAX_STRING_SIZE];
1239 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
1240 CLOG_ERROR(&LOG, "Couldn't initialize video codec: %s\n", error_str);
1241 BLI_strncpy(error, ffmpeg_last_error(), error_maxncpy);
1242 av_dict_free(&opts);
1243 avcodec_free_context(&c);
1244 context->video_codec = nullptr;
1245 return nullptr;
1246 }
1247 av_dict_free(&opts);
1248
1249 /* FFMPEG expects its data in the output pixel format. */
1250 context->current_frame = alloc_frame(c->pix_fmt, c->width, c->height);
1251
1252 if (c->pix_fmt == AV_PIX_FMT_RGBA && ELEM(c->colorspace, AVCOL_SPC_RGB, AVCOL_SPC_UNSPECIFIED)) {
1253 /* Output pixel format and colorspace is the same we use internally, no conversion needed. */
1254 context->img_convert_frame = nullptr;
1255 context->sws_ctx = nullptr;
1256 }
1257 else {
1258 /* Output pixel format is different, allocate frame for conversion.
1259 * Setup RGB->YUV conversion with proper coefficients, depending on range and colorspace. */
1260 const AVPixelFormat src_format = is_10_bpp || is_12_bpp || is_16_bpp ? AV_PIX_FMT_GBRAPF32LE :
1261 AV_PIX_FMT_RGBA;
1262 context->img_convert_frame = alloc_frame(src_format, c->width, c->height);
1263 context->sws_ctx = ffmpeg_sws_get_context(c->width,
1264 c->height,
1265 src_format,
1266 true,
1267 -1,
1268 c->width,
1269 c->height,
1270 c->pix_fmt,
1271 c->color_range == AVCOL_RANGE_JPEG,
1272 c->colorspace != AVCOL_SPC_RGB ? c->colorspace : -1,
1273 SWS_BICUBIC);
1274 }
1275
1276 avcodec_parameters_from_context(st->codecpar, c);
1277
1278 add_hdr_mastering_display_metadata(st->codecpar, c, imf);
1279 add_stereo3d_metadata(st->codecpar, *rd, *imf);
1280 add_spherical_mapping_metadata(st->codecpar, scene);
1281
1282 context->video_time = 0.0f;
1283
1284 return st;
1285}
1286
1287static void ffmpeg_add_metadata_callback(void *data,
1288 const char *propname,
1289 char *propvalue,
1290 int /*propvalue_maxncpy*/)
1291{
1292 AVDictionary **metadata = (AVDictionary **)data;
1293 av_dict_set(metadata, propname, propvalue, 0);
1294}
1295
1296static bool start_ffmpeg_impl(MovieWriter *context,
1297 const Scene *scene,
1299 const RenderData *rd,
1300 const ImageFormatData *imf,
1301 int rectx,
1302 int recty,
1303 const char *suffix,
1304 ReportList *reports)
1305{
1306 /* Handle to the output file */
1307 AVFormatContext *of;
1308 const AVOutputFormat *fmt;
1309 char filepath[FILE_MAX], error[1024];
1310 const char **exts;
1311 int ret = 0;
1312
1313 context->ffmpeg_type = rd->ffcodecdata.type;
1314 context->ffmpeg_codec = mov_av_codec_id_get(rd->ffcodecdata.codec_id_get());
1315 context->ffmpeg_audio_codec = mov_av_codec_id_get(rd->ffcodecdata.audio_codec_id_get());
1316 context->ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
1317 context->ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
1318 context->ffmpeg_gop_size = rd->ffcodecdata.gop_size;
1319 context->ffmpeg_autosplit = (rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0;
1320 context->ffmpeg_crf = rd->ffcodecdata.constant_rate_factor;
1321 context->custom_crf = rd->ffcodecdata.constant_rate_factor == FFM_CRF_CUSTOM;
1322 if (context->custom_crf) {
1323 context->ffmpeg_crf = rd->ffcodecdata.custom_constant_rate_factor;
1324 }
1325 context->ffmpeg_preset = rd->ffcodecdata.ffmpeg_preset;
1326 context->ffmpeg_profile = 0;
1327
1328 if ((rd->ffcodecdata.flags & FFMPEG_USE_MAX_B_FRAMES) != 0) {
1329 context->ffmpeg_max_b_frames = rd->ffcodecdata.max_b_frames;
1330 }
1331
1332 /* Determine the correct filename */
1333 if (!ffmpeg_filepath_get(
1334 context, filepath, scene, project, rd, context->ffmpeg_preview, suffix, reports))
1335 {
1336 return false;
1337 }
1338 CLOG_INFO(&LOG,
1339 "ffmpeg: starting output to %s:\n"
1340 " type=%d, codec=%d, audio_codec=%d,\n"
1341 " video_bitrate=%d, audio_bitrate=%d,\n"
1342 " gop_size=%d, autosplit=%d\n"
1343 " width=%d, height=%d",
1344 filepath,
1345 context->ffmpeg_type,
1346 context->ffmpeg_codec,
1347 context->ffmpeg_audio_codec,
1348 context->ffmpeg_video_bitrate,
1349 context->ffmpeg_audio_bitrate,
1350 context->ffmpeg_gop_size,
1351 context->ffmpeg_autosplit,
1352 rectx,
1353 recty);
1354
1355 /* Sanity checks for the output file extensions. */
1356 exts = get_file_extensions(context->ffmpeg_type);
1357 if (!exts) {
1358 BKE_report(reports, RPT_ERROR, "No valid formats found");
1359 return false;
1360 }
1361
1362 fmt = av_guess_format(nullptr, exts[0], nullptr);
1363 if (!fmt) {
1364 BKE_report(reports, RPT_ERROR, "No valid formats found");
1365 return false;
1366 }
1367
1368 of = avformat_alloc_context();
1369 if (!of) {
1370 BKE_report(reports, RPT_ERROR, "Cannot allocate FFmpeg format context");
1371 return false;
1372 }
1373
1374 enum AVCodecID audio_codec = context->ffmpeg_audio_codec;
1375 enum AVCodecID video_codec = context->ffmpeg_codec;
1376
1377 of->url = av_strdup(filepath);
1378 /* Check if we need to force change the codec because of file type codec restrictions */
1379 switch (context->ffmpeg_type) {
1380 case FFMPEG_OGG:
1381 video_codec = AV_CODEC_ID_THEORA;
1382 break;
1383 case FFMPEG_DV:
1384 video_codec = AV_CODEC_ID_DVVIDEO;
1385 break;
1386 case FFMPEG_MPEG1:
1387 video_codec = AV_CODEC_ID_MPEG1VIDEO;
1388 break;
1389 case FFMPEG_MPEG2:
1390 video_codec = AV_CODEC_ID_MPEG2VIDEO;
1391 break;
1392 case FFMPEG_H264:
1393 video_codec = AV_CODEC_ID_H264;
1394 break;
1395 case FFMPEG_XVID:
1396 video_codec = AV_CODEC_ID_MPEG4;
1397 break;
1398 case FFMPEG_FLV:
1399 video_codec = AV_CODEC_ID_FLV1;
1400 break;
1401 case FFMPEG_AV1:
1402 video_codec = AV_CODEC_ID_AV1;
1403 break;
1404 default:
1405 /* These containers are not restricted to any specific codec types.
1406 * Currently we expect these to be `.avi`, `.mov`, `.mkv`, and `.mp4`. */
1407 video_codec = context->ffmpeg_codec;
1408 break;
1409 }
1410
1411 if (context->custom_crf) {
1412 if ((video_codec == AV_CODEC_ID_AV1) || (video_codec == AV_CODEC_ID_H264) ||
1413 (video_codec == AV_CODEC_ID_H265))
1414 {
1415 context->ffmpeg_crf = math::clamp(context->ffmpeg_crf, 0, 51);
1416 }
1417 else if (video_codec == AV_CODEC_ID_VP9) {
1418 context->ffmpeg_crf = math::clamp(context->ffmpeg_crf, 0, 63);
1419 }
1420 else if (video_codec == AV_CODEC_ID_MPEG4) {
1421 context->ffmpeg_crf = math::clamp(context->ffmpeg_crf, 1, 31);
1422 }
1423 }
1424
1425 /* Returns after this must 'goto fail;' */
1426
1427# if LIBAVFORMAT_VERSION_MAJOR >= 59
1428 of->oformat = fmt;
1429# else
1430 /* *DEPRECATED* 2022/08/01 For FFMPEG (<5.0) remove this else branch and the `ifdef` above. */
1431 of->oformat = (AVOutputFormat *)fmt;
1432# endif
1433
1434 if (video_codec == AV_CODEC_ID_DVVIDEO) {
1435 if (rectx != 720) {
1436 BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
1437 goto fail;
1438 }
1439 if (rd->frs_sec != 25 && recty != 480) {
1440 BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
1441 goto fail;
1442 }
1443 if (rd->frs_sec == 25 && recty != 576) {
1444 BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
1445 goto fail;
1446 }
1447 }
1448
1449 if (context->ffmpeg_type == FFMPEG_DV) {
1450 audio_codec = AV_CODEC_ID_PCM_S16LE;
1451 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE &&
1452 rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2)
1453 {
1454 BKE_report(reports, RPT_ERROR, "FFmpeg only supports 48khz / stereo audio for DV!");
1455 goto fail;
1456 }
1457 }
1458
1459 if (video_codec == AV_CODEC_ID_PRORES) {
1460 context->ffmpeg_profile = rd->ffcodecdata.ffmpeg_prores_profile;
1461 }
1462
1463 if (video_codec != AV_CODEC_ID_NONE) {
1464 context->video_stream = alloc_video_stream(
1465 context, *scene, imf, video_codec, of, rectx, recty, error, sizeof(error));
1466 CLOG_INFO(&LOG, "ffmpeg: alloc video stream %p", context->video_stream);
1467 if (!context->video_stream) {
1468 if (error[0]) {
1469 BKE_report(reports, RPT_ERROR, error);
1470 CLOG_INFO(&LOG, "ffmpeg: video stream error: %s", error);
1471 }
1472 else {
1473 BKE_report(reports, RPT_ERROR, "Error initializing video stream");
1474 CLOG_STR_INFO(&LOG, "ffmpeg: error initializing video stream");
1475 }
1476 goto fail;
1477 }
1478 }
1479
1480 if (context->ffmpeg_audio_codec != AV_CODEC_ID_NONE) {
1481 context->audio_stream = alloc_audio_stream(context,
1482 rd->ffcodecdata.audio_mixrate,
1483 rd->ffcodecdata.audio_channels,
1484 audio_codec,
1485 of,
1486 error,
1487 sizeof(error),
1488 reports);
1489 if (!context->audio_stream) {
1490 if (error[0]) {
1491 BKE_report(reports, RPT_ERROR, error);
1492 CLOG_INFO(&LOG, "ffmpeg: audio stream error: %s", error);
1493 }
1494 else {
1495 BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
1496 CLOG_STR_INFO(&LOG, "ffmpeg: error initializing audio stream");
1497 }
1498 goto fail;
1499 }
1500 }
1501 if (!(fmt->flags & AVFMT_NOFILE)) {
1502 if (avio_open(&of->pb, filepath, AVIO_FLAG_WRITE) < 0) {
1503 BKE_report(reports, RPT_ERROR, "Could not open file for writing");
1504 CLOG_INFO(&LOG, "ffmpeg: could not open file %s for writing", filepath);
1505 goto fail;
1506 }
1507 }
1508
1509 if (context->stamp_data != nullptr) {
1511 &of->metadata, context->stamp_data, ffmpeg_add_metadata_callback, false);
1512 }
1513
1514 ret = avformat_write_header(of, nullptr);
1515 if (ret < 0) {
1516 BKE_report(reports,
1517 RPT_ERROR,
1518 "Could not initialize streams, probably unsupported codec combination");
1519 char error_str[AV_ERROR_MAX_STRING_SIZE];
1520 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
1521 CLOG_INFO(&LOG, "ffmpeg: could not write media header: %s", error_str);
1522 goto fail;
1523 }
1524
1525 context->outfile = of;
1526 av_dump_format(of, 0, filepath, 1);
1527
1528 return true;
1529
1530fail:
1531 if (of->pb) {
1532 avio_close(of->pb);
1533 }
1534
1535 context->video_stream = nullptr;
1536 context->audio_stream = nullptr;
1537
1538 avformat_free_context(of);
1539 return false;
1540}
1541
1542/* Flush any pending frames. An encoder may use both past and future frames
1543 * to predict inter-frames (H.264 B-frames, for example); it can output
1544 * the frames in a different order from the one it was given. The delayed
1545 * frames must be flushed before we close the stream. */
1546static void flush_delayed_frames(AVCodecContext *c, AVStream *stream, AVFormatContext *outfile)
1547{
1548 char error_str[AV_ERROR_MAX_STRING_SIZE];
1549 AVPacket *packet = av_packet_alloc();
1550
1551 avcodec_send_frame(c, nullptr);
1552
1553 /* Get the packets frames. */
1554 int ret = 1;
1555 while (ret >= 0) {
1556 ret = avcodec_receive_packet(c, packet);
1557
1558 if (ret == AVERROR(EAGAIN) || ret == AVERROR_EOF) {
1559 /* No more packets to flush. */
1560 break;
1561 }
1562 if (ret < 0) {
1563 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
1564 CLOG_ERROR(&LOG, "Error encoding delayed frame: %s", error_str);
1565 break;
1566 }
1567
1568 packet->stream_index = stream->index;
1569 av_packet_rescale_ts(packet, c->time_base, stream->time_base);
1570# ifdef FFMPEG_USE_DURATION_WORKAROUND
1571 my_guess_pkt_duration(outfile, stream, packet);
1572# endif
1573
1574 int write_ret = av_interleaved_write_frame(outfile, packet);
1575 if (write_ret != 0) {
1576 av_make_error_string(error_str, AV_ERROR_MAX_STRING_SIZE, ret);
1577 CLOG_ERROR(&LOG, "Error writing delayed frame: %s", error_str);
1578 break;
1579 }
1580 }
1581
1582 av_packet_free(&packet);
1583}
1584
1592static bool ffmpeg_filepath_get(MovieWriter *context,
1593 char filepath[FILE_MAX],
1594 const Scene *scene,
1596 const RenderData *rd,
1597 bool preview,
1598 const char *suffix,
1599 ReportList *reports)
1600{
1601 char autosplit[20];
1602
1603 const char **exts = get_file_extensions(rd->ffcodecdata.type);
1604 const char **fe = exts;
1605 int sfra, efra;
1606
1607 if (!filepath || !exts) {
1608 return false;
1609 }
1610
1611 if (preview) {
1612 sfra = rd->psfra;
1613 efra = rd->pefra;
1614 }
1615 else {
1616 sfra = rd->sfra;
1617 efra = rd->efra;
1618 }
1619
1620 BLI_strncpy(filepath, rd->pic, FILE_MAX);
1621
1622 bke::path_templates::VariableMap template_variables;
1623 BKE_add_template_variables_general(template_variables, &scene->id, project);
1624 BKE_add_template_variables_for_render_path(template_variables, *scene);
1625
1627 filepath, FILE_MAX, template_variables);
1628 if (!errors.is_empty()) {
1629 BKE_report_path_template_errors(reports, RPT_ERROR, filepath, errors);
1630 return false;
1631 }
1632
1634
1635 if (!BLI_file_ensure_parent_dir_exists(filepath)) {
1636 CLOG_ERROR(&LOG, "Couldn't create directory for file %s: %s", filepath, std::strerror(errno));
1637 return false;
1638 }
1639
1640 autosplit[0] = '\0';
1641
1642 if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
1643 if (context) {
1644 SNPRINTF(autosplit, "_%03d", context->ffmpeg_autosplit_count);
1645 }
1646 }
1647
1648 if (rd->scemode & R_EXTENSION) {
1649 while (*fe) {
1650 if (BLI_strcasecmp(filepath + strlen(filepath) - strlen(*fe), *fe) == 0) {
1651 break;
1652 }
1653 fe++;
1654 }
1655
1656 if (*fe == nullptr) {
1657 BLI_strncat(filepath, autosplit, FILE_MAX);
1658
1659 BLI_path_frame_range(filepath, FILE_MAX, sfra, efra, 4);
1660 BLI_strncat(filepath, *exts, FILE_MAX);
1661 }
1662 else {
1663 *(filepath + strlen(filepath) - strlen(*fe)) = '\0';
1664 BLI_strncat(filepath, autosplit, FILE_MAX);
1665 BLI_strncat(filepath, *fe, FILE_MAX);
1666 }
1667 }
1668 else {
1669 if (BLI_path_frame_check_chars(filepath)) {
1670 BLI_path_frame_range(filepath, FILE_MAX, sfra, efra, 4);
1671 }
1672
1673 BLI_strncat(filepath, autosplit, FILE_MAX);
1674 }
1675
1676 BLI_path_suffix(filepath, FILE_MAX, suffix, "");
1677
1678 return true;
1679}
1680
1681static void ffmpeg_get_filepath(char filepath[/*FILE_MAX*/ 1024],
1682 const Scene *scene,
1684 const RenderData *rd,
1685 bool preview,
1686 const char *suffix,
1687 ReportList *reports)
1688{
1689 ffmpeg_filepath_get(nullptr, filepath, scene, project, rd, preview, suffix, reports);
1690}
1691
1692static MovieWriter *ffmpeg_movie_open(const Scene *scene,
1694 const RenderData *rd,
1695 const ImageFormatData *imf,
1696 int rectx,
1697 int recty,
1698 ReportList *reports,
1699 bool preview,
1700 const char *suffix)
1701{
1702 MovieWriter *context = MEM_new<MovieWriter>("new FFMPEG context");
1703
1704 context->ffmpeg_codec = AV_CODEC_ID_MPEG4;
1705 context->ffmpeg_audio_codec = AV_CODEC_ID_NONE;
1706 context->ffmpeg_video_bitrate = 1150;
1707 context->ffmpeg_audio_bitrate = 128;
1708 context->ffmpeg_gop_size = 12;
1709 context->ffmpeg_autosplit = false;
1710 context->stamp_data = nullptr;
1711 context->audio_time_total = 0.0;
1712
1713 context->ffmpeg_autosplit_count = 0;
1714 context->ffmpeg_preview = preview;
1715 context->stamp_data = BKE_stamp_info_from_scene_static(scene);
1716
1717 bool success = start_ffmpeg_impl(
1718 context, scene, project, rd, imf, rectx, recty, suffix, reports);
1719
1720 if (success) {
1721 success = movie_audio_open(context,
1722 scene,
1723 preview ? rd->psfra : rd->sfra,
1724 rd->ffcodecdata.audio_mixrate,
1725 rd->ffcodecdata.audio_volume,
1726 reports);
1727 }
1728
1729 if (!success) {
1730 ffmpeg_movie_close(context);
1731 return nullptr;
1732 }
1733 return context;
1734}
1735
1736static void end_ffmpeg_impl(MovieWriter *context, bool is_autosplit);
1737
1738static bool ffmpeg_movie_append(MovieWriter *context,
1739 const Scene *scene,
1741 const RenderData *rd,
1742 const ImageFormatData *imf,
1743 int start_frame,
1744 int frame,
1745 const ImBuf *image,
1746 const char *suffix,
1747 ReportList *reports)
1748{
1749 AVFrame *avframe;
1750 bool success = true;
1751
1752 CLOG_INFO(&LOG, "ffmpeg: writing frame #%i (%ix%i)", frame, image->x, image->y);
1753
1754 if (context->video_stream) {
1755 avframe = generate_video_frame(context, image);
1756 success = (avframe && write_video_frame(context, avframe, reports));
1757 }
1758
1759 if (context->audio_stream) {
1760 /* Add +1 frame because we want to encode audio up until the next video frame. */
1761 write_audio_frames(
1762 context, (frame - start_frame + 1) / (double(rd->frs_sec) / double(rd->frs_sec_base)));
1763 }
1764
1765 if (context->ffmpeg_autosplit) {
1766 if (avio_tell(context->outfile->pb) > ffmpeg_autosplit_size) {
1767 end_ffmpeg_impl(context, true);
1768 context->ffmpeg_autosplit_count++;
1769
1770 success &= start_ffmpeg_impl(
1771 context, scene, project, rd, imf, image->x, image->y, suffix, reports);
1772 }
1773 }
1774
1775 return success;
1776}
1777
1778static void end_ffmpeg_impl(MovieWriter *context, bool is_autosplit)
1779{
1780 CLOG_STR_INFO(&LOG, "ffmpeg: closing");
1781
1782 movie_audio_close(context, is_autosplit);
1783
1784 if (context->video_stream) {
1785 CLOG_STR_INFO(&LOG, "ffmpeg: flush delayed video frames");
1786 flush_delayed_frames(context->video_codec, context->video_stream, context->outfile);
1787 }
1788
1789 if (context->audio_stream) {
1790 CLOG_STR_INFO(&LOG, "ffmpeg: flush delayed audio frames");
1791 flush_delayed_frames(context->audio_codec, context->audio_stream, context->outfile);
1792 }
1793
1794 if (context->outfile) {
1795 av_write_trailer(context->outfile);
1796 }
1797
1798 /* Close the video codec */
1799
1800 context->video_stream = nullptr;
1801 context->audio_stream = nullptr;
1802
1803 av_frame_free(&context->current_frame);
1804 av_frame_free(&context->img_convert_frame);
1805
1806 if (context->outfile != nullptr && context->outfile->oformat) {
1807 if (!(context->outfile->oformat->flags & AVFMT_NOFILE)) {
1808 avio_close(context->outfile->pb);
1809 }
1810 }
1811
1812 if (context->video_codec != nullptr) {
1813 avcodec_free_context(&context->video_codec);
1814 context->video_codec = nullptr;
1815 }
1816 if (context->audio_codec != nullptr) {
1817 avcodec_free_context(&context->audio_codec);
1818 context->audio_codec = nullptr;
1819 }
1820
1821 if (context->outfile != nullptr) {
1822 avformat_free_context(context->outfile);
1823 context->outfile = nullptr;
1824 }
1825 if (context->audio_input_buffer != nullptr) {
1826 av_free(context->audio_input_buffer);
1827 context->audio_input_buffer = nullptr;
1828 }
1829
1830 if (context->audio_deinterleave_buffer != nullptr) {
1831 av_free(context->audio_deinterleave_buffer);
1832 context->audio_deinterleave_buffer = nullptr;
1833 }
1834
1835 if (context->sws_ctx != nullptr) {
1836 ffmpeg_sws_release_context(context->sws_ctx);
1837 context->sws_ctx = nullptr;
1838 }
1839}
1840
1841static void ffmpeg_movie_close(MovieWriter *context)
1842{
1843 if (context == nullptr) {
1844 return;
1845 }
1846 end_ffmpeg_impl(context, false);
1847 if (context->stamp_data) {
1848 BKE_stamp_data_free(context->stamp_data);
1849 }
1850 MEM_delete(context);
1851}
1852
1853#endif /* WITH_FFMPEG */
1854
1855MovieWriter *MOV_write_begin(const Scene *scene,
1857 const RenderData *rd,
1858 const ImageFormatData *imf,
1859 int rectx,
1860 int recty,
1861 ReportList *reports,
1862 bool preview,
1863 const char *suffix)
1864{
1865 if (imf->imtype != R_IMF_IMTYPE_FFMPEG) {
1866 BKE_report(reports, RPT_ERROR, "Image format is not a movie format");
1867 return nullptr;
1868 }
1869
1870 MovieWriter *writer = nullptr;
1871#ifdef WITH_FFMPEG
1872 writer = ffmpeg_movie_open(scene, project, rd, imf, rectx, recty, reports, preview, suffix);
1873#else
1874 UNUSED_VARS(scene, project, rd, imf, rectx, recty, reports, preview, suffix);
1875#endif
1876 return writer;
1877}
1878
1879bool MOV_write_append(MovieWriter *writer,
1880 const Scene *scene,
1882 const RenderData *rd,
1883 const ImageFormatData *imf,
1884 int start_frame,
1885 int frame,
1886 const ImBuf *image,
1887 const char *suffix,
1888 ReportList *reports)
1889{
1890 if (writer == nullptr) {
1891 return false;
1892 }
1893
1894#ifdef WITH_FFMPEG
1895 bool ok = ffmpeg_movie_append(
1896 writer, scene, project, rd, imf, start_frame, frame, image, suffix, reports);
1897 return ok;
1898#else
1899 UNUSED_VARS(scene, project, rd, imf, start_frame, frame, image, suffix, reports);
1900 return false;
1901#endif
1902}
1903
1904void MOV_write_end(MovieWriter *writer)
1905{
1906#ifdef WITH_FFMPEG
1907 if (writer) {
1908 ffmpeg_movie_close(writer);
1909 }
1910#else
1911 UNUSED_VARS(writer);
1912#endif
1913}
1914
1915void MOV_filepath_from_settings(char filepath[/*FILE_MAX*/ 1024],
1916 const Scene *scene,
1918 const RenderData *rd,
1919 bool preview,
1920 const char *suffix,
1921 ReportList *reports)
1922{
1923#ifdef WITH_FFMPEG
1925 ffmpeg_get_filepath(filepath, scene, project, rd, preview, suffix, reports);
1926 return;
1927 }
1928#else
1929 UNUSED_VARS(scene, project, rd, preview, suffix, reports);
1930#endif
1931 filepath[0] = '\0';
1932}
1933
1934} // namespace blender
Functions and classes for evaluating template expressions in filepaths.
File and directory operations.
#define M_PI_2
#define M_PI
#define FILE_MAX
#define SNPRINTF(dst, format,...)
#define SNPRINTF_UTF8(dst, format,...)
#define CLOG_ERROR(clg_ref,...)
Definition CLG_log.h:188
#define CLOG_WARN(clg_ref,...)
Definition CLG_log.h:189
#define CLOG_STR_INFO(clg_ref, str)
Definition CLG_log.h:198
#define CLOG_INFO(clg_ref,...)
Definition CLG_log.h:190
Object is a sort of wrapper for general info.
Read Blender memory allocation and freeing.
#define BLI_assert_unreachable()
#define UNUSED_VARS(...)
#define ELEM(...)
#define BLI_assert_msg(a, msg)
#define STREQ(a, b)
Camera * camera
Definition scene.h:145
FFMPEG_INLINE size_t ffmpeg_get_buffer_alignment()
FFMPEG_INLINE enum AVPixelFormat * ffmpeg_get_pix_fmts(struct AVCodecContext *context, const AVCodec *codec)
FFMPEG_INLINE void my_guess_pkt_duration(AVFormatContext *s, AVStream *st, AVPacket *pkt)
#define INT_MAX
#define FLT_EPSILON
#define round
void camera(KernelGlobals &kg, const ShadingData &sd, float3 &outview, float &outdepth, float &outdist)
#define LOG(level)
Definition log.h:97
ccl_device_inline dual3 fabs(const ccl_private dual3 &a)
Definition math_dual.h:241
void free(Subdiv *subdiv)
Definition subdiv.cc:192
int context(const bContext *C, const char *member, bContextDataResult *result)
T clamp(const T &a, const T &min, const T &max)
BMesh Iterators.
BLI_assert(slot->slot_subtype.map==BMO_OP_SLOT_SUBTYPE_MAP_FLT)
int char char int BLI_strcasecmp(const char *s1, const char *s2) ATTR_WARN_UNUSED_RESULT ATTR_NONNULL(1
bool void bool BLI_path_frame_check_chars(const char *path) ATTR_NONNULL(1) ATTR_WARN_UNUSED_RESULT
size_t size_t size_t BLI_snprintf_utf8(char *__restrict dst, size_t dst_maxncpy, const char *__restrict format,...) ATTR_NONNULL(1
void MOV_filepath_from_settings(char filepath[1024], const Scene *scene, const bke::BlenderProject *project, const RenderData *rd, bool preview, const char *suffix, ReportList *reports)
__int64 int64_t
Definition BKE_text.h:90
void IMB_buffer_float_from_byte(float *dest, const unsigned char *src, int width, int height, int dest_stride, int src_stride)
@ FFM_CRF_PERC_LOSSLESS
unsigned int uint
Definition BKE_text.h:55
void * MEM_new_array_uninitialized(size_t len, size_t size, const char *str) ATTR_WARN_UNUSED_RESULT ATTR_ALLOC_SIZE(1
bool BLI_path_abs(char path[FILE_MAX], const char *basepath) ATTR_NONNULL(1
void BKE_add_template_variables_general(bke::path_templates::VariableMap &variables, const ID *path_owner_id, const bke::BlenderProject *project)
bool MOV_codec_supports_alpha(IMB_Ffmpeg_Codec_ID codec_id, int ffmpeg_profile)
size_t IMB_get_pixel_count(const ImBuf *ibuf)
Get the length of the data of the given image buffer in pixels.
MINLINE int power_of_2_min_i(int n)
bool bool BLI_path_suffix(char *path, size_t path_maxncpy, const char *suffix, const char *sep) ATTR_NONNULL(1
@ S3D_DISPLAY_SIDEBYSIDE
@ S3D_DISPLAY_TOPBOTTOM
@ S3D_DISPLAY_INTERLACE
void BKE_report_path_template_errors(ReportList *reports, eReportType report_type, StringRef path, Span< bke::path_templates::Error > errors)
const char * BKE_main_blendfile_path_from_global()
Definition main.cc:1063
MINLINE int max_ii(int a, int b)
bool IMB_colormanagement_space_to_cicp(const ColorSpace *colorspace, ColorManagedFileOutput output, bool rgb_matrix, int cicp[4])
bool BLI_path_frame_range(char *path, size_t path_maxncpy, int sta, int end, int digits) ATTR_NONNULL(1)
MovieWriter * MOV_write_begin(const Scene *scene, const bke::BlenderProject *project, const RenderData *rd, const ImageFormatData *imf, int rectx, int recty, ReportList *reports, bool preview, const char *suffix)
void MOV_write_end(MovieWriter *writer)
void BKE_add_template_variables_for_render_path(bke::path_templates::VariableMap &variables, const Scene &scene)
Vector< bke::path_templates::Error > BKE_path_apply_template(char *path, int path_maxncpy, const bke::path_templates::VariableMap &template_variables)
void BKE_stamp_data_free(StampData *stamp_data)
@ CAM_PANORAMA_EQUIRECTANGULAR
char * BLI_strncpy(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
void IMB_freeImBuf(ImBuf *ibuf)
bool MOV_write_append(MovieWriter *writer, const Scene *scene, const bke::BlenderProject *project, const RenderData *rd, const ImageFormatData *imf, int start_frame, int frame, const ImBuf *image, const char *suffix, ReportList *reports)
@ FFM_PRESET_REALTIME
void BKE_report(ReportList *reports, eReportType type, const char *message)
Definition report.cc:162
BMesh const char void * data
@ FFMPEG_OGG
Definition MOV_enums.hh:24
@ FFMPEG_XVID
Definition MOV_enums.hh:21
@ FFMPEG_MPEG4
Definition MOV_enums.hh:16
@ FFMPEG_MKV
Definition MOV_enums.hh:23
@ FFMPEG_H264
Definition MOV_enums.hh:20
@ FFMPEG_WEBM
Definition MOV_enums.hh:26
@ FFMPEG_MPEG2
Definition MOV_enums.hh:15
@ FFMPEG_MPEG1
Definition MOV_enums.hh:14
@ FFMPEG_AV1
Definition MOV_enums.hh:27
@ FFMPEG_FLV
Definition MOV_enums.hh:22
@ FFMPEG_DV
Definition MOV_enums.hh:19
@ FFMPEG_AVI
Definition MOV_enums.hh:17
@ FFMPEG_MOV
Definition MOV_enums.hh:18
unsigned char uint8_t
Definition BKE_text.h:79
@ S3D_INTERLACE_CHECKERBOARD
@ S3D_SIDEBYSIDE_CROSSEYED
int IMB_colormanagement_view_max_nits(const char *display_name, const char *view_name)
ATTR_WARN_UNUSED_RESULT const size_t num
bool BKE_scene_multiview_is_stereo3d(const RenderData *rd)
Definition scene.cc:3224
bool MOV_codec_supports_crf(IMB_Ffmpeg_Codec_ID codec_id)
ImBuf * IMB_allocImBuf(unsigned int x, unsigned int y, ImBufFlags flags)
const ColorSpace * IMB_colormangement_display_get_color_space(const ColorManagedViewSettings *view_settings, const ColorManagedDisplaySettings *display_settings)
MINLINE unsigned int log2_floor_u(unsigned int x)
void BKE_stamp_info_callback(void *data, StampData *stamp_data, StampCallback callback, bool noskip)
@ FFMPEG_AUTOSPLIT_OUTPUT
@ FFMPEG_LOSSLESS_OUTPUT
@ FFMPEG_USE_MAX_B_FRAMES
StampData * BKE_stamp_info_from_scene_static(const Scene *scene)
@ R_IMF_VIEWS_STEREO_3D
MINLINE int is_power_of_2_i(int n)
@ FFM_PRORES_PROFILE_422_HQ
@ FFM_PRORES_PROFILE_4444_XQ
@ FFM_PRORES_PROFILE_4444
@ FFM_PRORES_PROFILE_422_PROXY
MINLINE int min_ii(int a, int b)
MINLINE int clamp_i(int value, int min, int max)
bool BLI_file_ensure_parent_dir_exists(const char *filepath) ATTR_NONNULL(1)
Definition fileops_c.cc:454
ATTR_WARN_UNUSED_RESULT const BMVert const BMEdge * e
MINLINE int compare_ff(float a, float b, float max_diff)
char char size_t char * BLI_strncat(char *__restrict dst, const char *__restrict src, size_t dst_maxncpy) ATTR_NONNULL(1
ocio::ColorSpace ColorSpace
Definition BLF_api.hh:42
MINLINE void premul_to_straight_v4_v4(float straight[4], const float premul[4])
const btScalar eps
Definition poly34.cpp:11
#define fabsf
#define sqrtf
KERNEL_FEATURE_LIGHT_PASSES KERNEL_FEATURE_PATH_GUIDING float
#define min(a, b)
Definition sort.cc:38
ImageFormatData im_format