1 /** \file blender/blenkernel/intern/writeffmpeg.c
9 * Partial Copyright (c) 2006 Peter Schlaile
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
27 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
28 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
36 #include <libavformat/avformat.h>
37 #include <libavcodec/avcodec.h>
38 #include <libavutil/rational.h>
39 #include <libswscale/swscale.h>
40 #include <libavcodec/opt.h>
42 #if defined(WIN32) && (!(defined snprintf))
43 #define snprintf _snprintf
46 #include "MEM_guardedalloc.h"
48 #include "DNA_scene_types.h"
50 #include "BLI_blenlib.h"
52 #include "AUD_C-API.h" /* must be before BKE_sound.h for define */
54 #include "BKE_global.h"
55 #include "BKE_idprop.h"
57 #include "BKE_report.h"
58 #include "BKE_sound.h"
59 #include "BKE_writeffmpeg.h"
61 #include "IMB_imbuf_types.h"
62 #include "IMB_imbuf.h"
64 #if (LIBAVFORMAT_VERSION_MAJOR > 52) || ((LIBAVFORMAT_VERSION_MAJOR >= 52) && (LIBAVFORMAT_VERSION_MINOR >= 105))
65 #define FFMPEG_HAVE_AVIO 1
68 #if (LIBAVFORMAT_VERSION_MAJOR > 53) || ((LIBAVFORMAT_VERSION_MAJOR >= 53) && (LIBAVFORMAT_VERSION_MINOR >= 1))
69 #define FFMPEG_HAVE_DEFAULT_VAL_UNION 1
72 #if (LIBAVFORMAT_VERSION_MAJOR > 52) || ((LIBAVFORMAT_VERSION_MAJOR >= 52) && (LIBAVFORMAT_VERSION_MINOR >= 101))
73 #define FFMPEG_HAVE_AV_DUMP_FORMAT 1
76 #ifndef FFMPEG_HAVE_AVIO
77 #define AVIO_FLAG_WRITE URL_WRONLY
78 #define avio_open url_fopen
79 #define avio_tell url_ftell
80 #define avio_close url_fclose
83 /* make OpenSuSe special "in-between" ffmpeg 0.6.2 version(tm) happy...
85 #ifndef AVIO_FLAG_WRITE
86 #define AVIO_FLAG_WRITE URL_WRONLY
89 #ifndef FFMPEG_HAVE_AV_DUMP_FORMAT
90 #define av_dump_format dump_format
93 extern void do_init_ffmpeg(void);
95 static int ffmpeg_type = 0;
96 static int ffmpeg_codec = CODEC_ID_MPEG4;
97 static int ffmpeg_audio_codec = CODEC_ID_NONE;
98 static int ffmpeg_video_bitrate = 1150;
99 static int ffmpeg_audio_bitrate = 128;
100 static int ffmpeg_gop_size = 12;
101 static int ffmpeg_autosplit = 0;
102 static int ffmpeg_autosplit_count = 0;
104 static AVFormatContext* outfile = 0;
105 static AVStream* video_stream = 0;
106 static AVStream* audio_stream = 0;
107 static AVFrame* current_frame = 0;
108 static struct SwsContext *img_convert_ctx = 0;
110 static uint8_t* video_buffer = 0;
111 static int video_buffersize = 0;
113 static uint8_t* audio_input_buffer = 0;
114 static int audio_input_samples = 0;
115 static uint8_t* audio_output_buffer = 0;
116 static int audio_outbuf_size = 0;
117 static double audio_time = 0.0f;
119 static AUD_Device* audio_mixdown_device = 0;
121 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
123 /* Delete a picture buffer */
125 static void delete_picture(AVFrame* f)
128 if (f->data[0]) MEM_freeN(f->data[0]);
133 static int write_audio_frame(void)
135 AVCodecContext* c = NULL;
138 c = audio_stream->codec;
140 av_init_packet(&pkt);
143 AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
144 audio_time += (double) audio_input_samples / (double) c->sample_rate;
146 pkt.size = avcodec_encode_audio(c, audio_output_buffer,
148 (short*) audio_input_buffer);
152 // XXX error("Error writing audio packet");
156 pkt.data = audio_output_buffer;
158 if(c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
160 pkt.pts = av_rescale_q(c->coded_frame->pts,
161 c->time_base, audio_stream->time_base);
162 fprintf(stderr, "Audio Frame PTS: %d\n", (int)pkt.pts);
165 pkt.stream_index = audio_stream->index;
167 pkt.flags |= AV_PKT_FLAG_KEY;
169 if (av_interleaved_write_frame(outfile, &pkt) != 0) {
170 fprintf(stderr, "Error writing audio packet!\n");
176 /* Allocate a temporary frame */
177 static AVFrame* alloc_picture(int pix_fmt, int width, int height)
183 /* allocate space for the struct */
184 f = avcodec_alloc_frame();
186 size = avpicture_get_size(pix_fmt, width, height);
187 /* allocate the actual picture buffer */
188 buf = MEM_mallocN(size, "AVFrame buffer");
193 avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
197 /* Get the correct file extensions for the requested format,
198 first is always desired guess_format parameter */
199 static const char** get_file_extensions(int format)
203 static const char * rv[] = { ".dv", NULL };
207 static const char * rv[] = { ".mpg", ".mpeg", NULL };
211 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
216 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
220 static const char * rv[] = { ".avi", NULL };
224 static const char * rv[] = { ".mov", NULL };
228 /* FIXME: avi for now... */
229 static const char * rv[] = { ".avi", NULL };
234 /* FIXME: avi for now... */
235 static const char * rv[] = { ".avi", NULL };
239 static const char * rv[] = { ".flv", NULL };
243 static const char * rv[] = { ".mkv", NULL };
247 static const char * rv[] = { ".ogg", ".ogv", NULL };
251 static const char * rv[] = { ".mp3", NULL };
255 static const char * rv[] = { ".wav", NULL };
263 /* Write a frame to the output file */
264 static int write_video_frame(RenderData *rd, AVFrame* frame, ReportList *reports)
268 AVCodecContext* c = video_stream->codec;
270 frame->pts = rd->cfra - rd->sfra;
272 if (rd->mode & R_FIELDS) {
273 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
276 outsize = avcodec_encode_video(c, video_buffer, video_buffersize,
280 av_init_packet(&packet);
282 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
283 packet.pts = av_rescale_q(c->coded_frame->pts,
285 video_stream->time_base);
286 fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
288 fprintf(stderr, "Video Frame PTS: not set\n");
290 if (c->coded_frame->key_frame)
291 packet.flags |= AV_PKT_FLAG_KEY;
292 packet.stream_index = video_stream->index;
293 packet.data = video_buffer;
294 packet.size = outsize;
295 ret = av_interleaved_write_frame(outfile, &packet);
302 BKE_report(reports, RPT_ERROR, "Error writing frame.");
308 /* read and encode a frame of audio from the buffer */
309 static AVFrame* generate_video_frame(uint8_t* pixels, ReportList *reports)
311 uint8_t* rendered_frame;
313 AVCodecContext* c = video_stream->codec;
314 int width = c->width;
315 int height = c->height;
318 if (c->pix_fmt != PIX_FMT_BGR32) {
319 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
321 BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
325 rgb_frame = current_frame;
328 rendered_frame = pixels;
330 /* Do RGBA-conversion and flipping in one step depending
333 if (ENDIAN_ORDER == L_ENDIAN) {
335 for (y = 0; y < height; y++) {
336 uint8_t* target = rgb_frame->data[0]
337 + width * 4 * (height - y - 1);
338 uint8_t* src = rendered_frame + width * 4 * y;
339 uint8_t* end = src + width * 4;
352 for (y = 0; y < height; y++) {
353 uint8_t* target = rgb_frame->data[0]
354 + width * 4 * (height - y - 1);
355 uint8_t* src = rendered_frame + width * 4 * y;
356 uint8_t* end = src + width * 4;
369 if (c->pix_fmt != PIX_FMT_BGR32) {
370 sws_scale(img_convert_ctx, (const uint8_t * const*) rgb_frame->data,
371 rgb_frame->linesize, 0, c->height,
372 current_frame->data, current_frame->linesize);
373 delete_picture(rgb_frame);
375 return current_frame;
378 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
382 const AVOption * rv = NULL;
384 fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
386 BLI_strncpy(name, prop->name, sizeof(name));
388 param = strchr(name, ':');
396 fprintf(stderr, "%s.\n", IDP_String(prop));
397 av_set_string3(c, prop->name, IDP_String(prop), 1, &rv);
400 fprintf(stderr, "%g.\n", IDP_Float(prop));
401 rv = av_set_double(c, prop->name, IDP_Float(prop));
404 fprintf(stderr, "%d.\n", IDP_Int(prop));
408 av_set_string3(c, name, param, 1, &rv);
413 rv = av_set_int(c, prop->name, IDP_Int(prop));
419 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
424 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char * prop_name)
430 if (!rd->ffcodecdata.properties) {
434 prop = IDP_GetPropertyFromGroup(
435 rd->ffcodecdata.properties, (char*) prop_name);
440 iter = IDP_GetGroupIterator(prop);
442 while ((curr = IDP_GroupIterNext(iter)) != NULL) {
443 set_ffmpeg_property_option(c, curr);
447 /* prepare a video stream for the output file */
449 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
450 int rectx, int recty)
455 st = av_new_stream(of, 0);
456 if (!st) return NULL;
458 /* Set up the codec context */
461 c->codec_id = codec_id;
462 c->codec_type = AVMEDIA_TYPE_VIDEO;
465 /* Get some values from the current render settings */
470 /* FIXME: Really bad hack (tm) for NTSC support */
471 if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
472 c->time_base.den = 2997;
473 c->time_base.num = 100;
474 } else if ((double) ((int) rd->frs_sec_base) ==
476 c->time_base.den = rd->frs_sec;
477 c->time_base.num = (int) rd->frs_sec_base;
479 c->time_base.den = rd->frs_sec * 100000;
480 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
483 c->gop_size = ffmpeg_gop_size;
484 c->bit_rate = ffmpeg_video_bitrate*1000;
485 c->rc_max_rate = rd->ffcodecdata.rc_max_rate*1000;
486 c->rc_min_rate = rd->ffcodecdata.rc_min_rate*1000;
487 c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
488 c->rc_initial_buffer_occupancy
489 = rd->ffcodecdata.rc_buffer_size*3/4;
490 c->rc_buffer_aggressivity = 1.0;
491 c->me_method = ME_EPZS;
493 codec = avcodec_find_encoder(c->codec_id);
494 if (!codec) return NULL;
496 /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
498 if (codec->pix_fmts) {
499 c->pix_fmt = codec->pix_fmts[0];
501 /* makes HuffYUV happy ... */
502 c->pix_fmt = PIX_FMT_YUV422P;
505 if (ffmpeg_type == FFMPEG_XVID) {
507 c->pix_fmt = PIX_FMT_YUV420P;
508 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
511 if (codec_id == CODEC_ID_H264) {
512 /* correct wrong default ffmpeg param which crash x264 */
517 if ((of->oformat->flags & AVFMT_GLOBALHEADER)
518 // || !strcmp(of->oformat->name, "mp4")
519 // || !strcmp(of->oformat->name, "mov")
520 // || !strcmp(of->oformat->name, "3gp")
522 fprintf(stderr, "Using global header\n");
523 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
526 /* Determine whether we are encoding interlaced material or not */
527 if (rd->mode & R_FIELDS) {
528 fprintf(stderr, "Encoding interlaced video\n");
529 c->flags |= CODEC_FLAG_INTERLACED_DCT;
530 c->flags |= CODEC_FLAG_INTERLACED_ME;
533 /* xasp & yasp got float lately... */
535 st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
536 ((double) rd->xasp / (double) rd->yasp), 255);
538 set_ffmpeg_properties(rd, c, "video");
540 if (avcodec_open(c, codec) < 0) {
542 //XXX error("Couldn't initialize codec");
546 video_buffersize = 2000000;
547 video_buffer = (uint8_t*)MEM_mallocN(video_buffersize,
548 "FFMPEG video buffer");
550 current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
552 img_convert_ctx = sws_getContext(c->width, c->height,
561 /* Prepare an audio stream for the output file */
563 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of)
569 st = av_new_stream(of, 1);
570 if (!st) return NULL;
573 c->codec_id = codec_id;
574 c->codec_type = AVMEDIA_TYPE_AUDIO;
576 c->sample_rate = rd->ffcodecdata.audio_mixrate;
577 c->bit_rate = ffmpeg_audio_bitrate*1000;
578 c->sample_fmt = SAMPLE_FMT_S16;
580 codec = avcodec_find_encoder(c->codec_id);
582 //XXX error("Couldn't find a valid audio codec");
586 set_ffmpeg_properties(rd, c, "audio");
588 if (avcodec_open(c, codec) < 0) {
589 //XXX error("Couldn't initialize audio codec");
593 audio_outbuf_size = FF_MIN_BUFFER_SIZE;
595 if((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
596 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
599 audio_input_samples = c->frame_size;
600 if(c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
601 audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
604 audio_output_buffer = (uint8_t*)MEM_mallocN(
605 audio_outbuf_size, "FFMPEG audio encoder input buffer");
607 audio_input_buffer = (uint8_t*)MEM_mallocN(
608 audio_input_samples * c->channels * sizeof(int16_t),
609 "FFMPEG audio encoder output buffer");
615 /* essential functions -- start, append, end */
617 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
619 /* Handle to the output file */
625 ffmpeg_type = rd->ffcodecdata.type;
626 ffmpeg_codec = rd->ffcodecdata.codec;
627 ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
628 ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
629 ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
630 ffmpeg_gop_size = rd->ffcodecdata.gop_size;
631 ffmpeg_autosplit = rd->ffcodecdata.flags
632 & FFMPEG_AUTOSPLIT_OUTPUT;
636 /* Determine the correct filename */
637 filepath_ffmpeg(name, rd);
638 fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
639 " Using type=%d, codec=%d, audio_codec=%d,\n"
640 " video_bitrate=%d, audio_bitrate=%d,\n"
641 " gop_size=%d, autosplit=%d\n"
642 " render width=%d, render height=%d\n",
643 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
644 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
645 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
647 exts = get_file_extensions(ffmpeg_type);
649 BKE_report(reports, RPT_ERROR, "No valid formats found.");
652 fmt = av_guess_format(NULL, exts[0], NULL);
654 BKE_report(reports, RPT_ERROR, "No valid formats found.");
658 of = avformat_alloc_context();
660 BKE_report(reports, RPT_ERROR, "Error opening output file");
665 of->packet_size= rd->ffcodecdata.mux_packet_size;
666 if (ffmpeg_audio_codec != CODEC_ID_NONE) {
667 of->mux_rate = rd->ffcodecdata.mux_rate;
672 of->preload = (int)(0.5*AV_TIME_BASE);
673 of->max_delay = (int)(0.7*AV_TIME_BASE);
675 fmt->audio_codec = ffmpeg_audio_codec;
677 snprintf(of->filename, sizeof(of->filename), "%s", name);
678 /* set the codec to the user's selection */
679 switch(ffmpeg_type) {
684 fmt->video_codec = ffmpeg_codec;
687 fmt->video_codec = CODEC_ID_DVVIDEO;
690 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
693 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
696 fmt->video_codec = CODEC_ID_H264;
699 fmt->video_codec = CODEC_ID_MPEG4;
702 fmt->video_codec = CODEC_ID_FLV1;
705 fmt->audio_codec = CODEC_ID_MP3;
707 fmt->video_codec = CODEC_ID_NONE;
711 fmt->video_codec = CODEC_ID_MPEG4;
714 if (fmt->video_codec == CODEC_ID_DVVIDEO) {
716 BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
719 if (rd->frs_sec != 25 && recty != 480) {
720 BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
723 if (rd->frs_sec == 25 && recty != 576) {
724 BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
729 if (ffmpeg_type == FFMPEG_DV) {
730 fmt->audio_codec = CODEC_ID_PCM_S16LE;
731 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000) {
732 BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
737 if (fmt->video_codec != CODEC_ID_NONE) {
738 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
739 printf("alloc video stream %p\n", video_stream);
741 BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
746 if (ffmpeg_audio_codec != CODEC_ID_NONE) {
747 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
749 BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
753 if (av_set_parameters(of, NULL) < 0) {
754 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
757 if (!(fmt->flags & AVFMT_NOFILE)) {
758 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
759 BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
766 av_dump_format(of, 0, name, 1);
772 * Writes any delayed frames in the encoder. This function is called before
773 * closing the encoder.
776 * Since an encoder may use both past and future frames to predict
777 * inter-frames (H.264 B-frames, for example), it can output the frames
778 * in a different order from the one it was given.
779 * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
780 * them in the order 1, 4, 2, 3 - first the two frames used for predition,
781 * and then the bidirectionally-predicted frames. What this means in practice
782 * is that the encoder may not immediately produce one output frame for each
783 * input frame. These delayed frames must be flushed before we close the
784 * stream. We do this by calling avcodec_encode_video with NULL for the last
788 void flush_ffmpeg(void)
793 AVCodecContext* c = video_stream->codec;
794 /* get the delayed frames */
797 av_init_packet(&packet);
799 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
801 fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
807 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
808 packet.pts = av_rescale_q(c->coded_frame->pts,
810 video_stream->time_base);
811 fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
813 fprintf(stderr, "Video Frame PTS: not set\n");
815 if (c->coded_frame->key_frame) {
816 packet.flags |= AV_PKT_FLAG_KEY;
818 packet.stream_index = video_stream->index;
819 packet.data = video_buffer;
820 packet.size = outsize;
821 ret = av_interleaved_write_frame(outfile, &packet);
823 fprintf(stderr, "Error writing delayed frame %d\n", ret);
827 avcodec_flush_buffers(video_stream->codec);
830 /* **********************************************************************
832 ********************************************************************** */
834 /* Get the output filename-- similar to the other output formats */
835 void filepath_ffmpeg(char* string, RenderData* rd) {
838 const char ** exts = get_file_extensions(rd->ffcodecdata.type);
839 const char ** fe = exts;
841 if (!string || !exts) return;
843 strcpy(string, rd->pic);
844 BLI_path_abs(string, G.main->name);
846 BLI_make_existing_file(string);
850 if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
851 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
855 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe),
863 strcat(string, autosplit);
865 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
866 strcat(string, *exts);
868 *(string + strlen(string) - strlen(*fe)) = 0;
869 strcat(string, autosplit);
874 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
878 ffmpeg_autosplit_count = 0;
880 success = start_ffmpeg_impl(rd, rectx, recty, reports);
884 AVCodecContext* c = audio_stream->codec;
885 AUD_DeviceSpecs specs;
886 specs.channels = c->channels;
887 specs.format = AUD_FORMAT_S16;
888 specs.rate = rd->ffcodecdata.audio_mixrate;
889 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
895 void end_ffmpeg(void);
897 static void write_audio_frames(double to_pts)
901 while (audio_stream && !finished) {
902 if((audio_time >= to_pts) ||
903 (write_audio_frame())) {
909 int append_ffmpeg(RenderData *rd, int frame, int *pixels, int rectx, int recty, ReportList *reports)
914 fprintf(stderr, "Writing frame %i, "
915 "render width=%d, render height=%d\n", frame,
918 // why is this done before writing the video frame and again at end_ffmpeg?
919 // write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
923 avframe= generate_video_frame((unsigned char*) pixels, reports);
924 success= (avframe && write_video_frame(rd, avframe, reports));
926 if (ffmpeg_autosplit) {
927 if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
929 ffmpeg_autosplit_count++;
930 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
935 write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
940 void end_ffmpeg(void)
944 fprintf(stderr, "Closing ffmpeg...\n");
946 /* if (audio_stream) { SEE UPPER
947 write_audio_frames();
950 if(audio_mixdown_device)
952 AUD_closeReadDevice(audio_mixdown_device);
953 audio_mixdown_device = 0;
956 if (video_stream && video_stream->codec) {
957 fprintf(stderr, "Flushing delayed frames...\n");
962 av_write_trailer(outfile);
965 /* Close the video codec */
967 if (video_stream && video_stream->codec) {
968 avcodec_close(video_stream->codec);
969 printf("zero video stream %p\n", video_stream);
974 /* Close the output file */
976 for (i = 0; i < outfile->nb_streams; i++) {
977 if (&outfile->streams[i]) {
978 av_freep(&outfile->streams[i]);
982 /* free the temp buffer */
984 delete_picture(current_frame);
987 if (outfile && outfile->oformat) {
988 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
989 avio_close(outfile->pb);
997 MEM_freeN(video_buffer);
1000 if (audio_output_buffer) {
1001 MEM_freeN(audio_output_buffer);
1002 audio_output_buffer = 0;
1004 if (audio_input_buffer) {
1005 MEM_freeN(audio_input_buffer);
1006 audio_input_buffer = 0;
1009 if (img_convert_ctx) {
1010 sws_freeContext(img_convert_ctx);
1011 img_convert_ctx = 0;
1017 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1019 struct IDProperty *prop = (struct IDProperty *) prop_;
1022 if (!rd->ffcodecdata.properties) {
1026 group = IDP_GetPropertyFromGroup(
1027 rd->ffcodecdata.properties, (char*) type);
1028 if (group && prop) {
1029 IDP_RemFromGroup(group, prop);
1030 IDP_FreeProperty(prop);
1035 IDProperty *ffmpeg_property_add(RenderData *rd, char * type, int opt_index, int parent_index)
1039 const AVOption * parent;
1042 IDPropertyTemplate val;
1048 avcodec_get_context_defaults(&c);
1050 o = c.av_class->option + opt_index;
1051 parent = c.av_class->option + parent_index;
1053 if (!rd->ffcodecdata.properties) {
1054 rd->ffcodecdata.properties
1055 = IDP_New(IDP_GROUP, val, "ffmpeg");
1058 group = IDP_GetPropertyFromGroup(
1059 rd->ffcodecdata.properties, (char*) type);
1062 group = IDP_New(IDP_GROUP, val, (char*) type);
1063 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1067 sprintf(name, "%s:%s", parent->name, o->name);
1069 strcpy(name, o->name);
1072 fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1073 type, parent_index, opt_index, name);
1075 prop = IDP_GetPropertyFromGroup(group, name);
1081 case FF_OPT_TYPE_INT:
1082 case FF_OPT_TYPE_INT64:
1083 #ifdef FFMPEG_HAVE_DEFAULT_VAL_UNION
1084 val.i = o->default_val.i64;
1086 val.i = o->default_val;
1090 case FF_OPT_TYPE_DOUBLE:
1091 case FF_OPT_TYPE_FLOAT:
1092 #ifdef FFMPEG_HAVE_DEFAULT_VAL_UNION
1093 val.f = o->default_val.dbl;
1095 val.f = o->default_val;
1097 idp_type = IDP_FLOAT;
1099 case FF_OPT_TYPE_STRING:
1101 idp_type = IDP_STRING;
1103 case FF_OPT_TYPE_CONST:
1110 prop = IDP_New(idp_type, val, name);
1111 IDP_AddToGroup(group, prop);
1115 /* not all versions of ffmpeg include that, so here we go ... */
1117 static const AVOption *my_av_find_opt(void *v, const char *name,
1118 const char *unit, int mask, int flags){
1119 AVClass *c= *(AVClass**)v;
1120 const AVOption *o= c->option;
1122 for(;o && o->name; o++){
1123 if(!strcmp(o->name, name) &&
1124 (!unit || (o->unit && !strcmp(o->unit, unit))) &&
1125 (o->flags & mask) == flags )
1131 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1134 const AVOption * o = 0;
1135 const AVOption * p = 0;
1141 avcodec_get_context_defaults(&c);
1143 strncpy(name_, str, sizeof(name_));
1146 while (*name == ' ') name++;
1148 param = strchr(name, ':');
1151 param = strchr(name, ' ');
1155 while (*param == ' ') param++;
1158 o = my_av_find_opt(&c, name, NULL, 0, 0);
1162 if (param && o->type == FF_OPT_TYPE_CONST) {
1165 if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1166 p = my_av_find_opt(&c, param, o->unit, 0, 0);
1167 prop = ffmpeg_property_add(rd,
1168 (char*) type, p - c.av_class->option,
1169 o - c.av_class->option);
1171 prop = ffmpeg_property_add(rd,
1172 (char*) type, o - c.av_class->option, 0);
1181 switch (prop->type) {
1183 IDP_Int(prop) = atoi(param);
1186 IDP_Float(prop) = atof(param);
1189 strncpy(IDP_String(prop), param, prop->len);
1196 void ffmpeg_set_preset(RenderData *rd, int preset)
1198 int isntsc = (rd->frs_sec != 25);
1201 case FFMPEG_PRESET_VCD:
1202 rd->ffcodecdata.type = FFMPEG_MPEG1;
1203 rd->ffcodecdata.video_bitrate = 1150;
1205 rd->ysch = isntsc ? 240 : 288;
1206 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1207 rd->ffcodecdata.rc_max_rate = 1150;
1208 rd->ffcodecdata.rc_min_rate = 1150;
1209 rd->ffcodecdata.rc_buffer_size = 40*8;
1210 rd->ffcodecdata.mux_packet_size = 2324;
1211 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1214 case FFMPEG_PRESET_SVCD:
1215 rd->ffcodecdata.type = FFMPEG_MPEG2;
1216 rd->ffcodecdata.video_bitrate = 2040;
1218 rd->ysch = isntsc ? 480 : 576;
1219 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1220 rd->ffcodecdata.rc_max_rate = 2516;
1221 rd->ffcodecdata.rc_min_rate = 0;
1222 rd->ffcodecdata.rc_buffer_size = 224*8;
1223 rd->ffcodecdata.mux_packet_size = 2324;
1224 rd->ffcodecdata.mux_rate = 0;
1227 case FFMPEG_PRESET_DVD:
1228 rd->ffcodecdata.type = FFMPEG_MPEG2;
1229 rd->ffcodecdata.video_bitrate = 6000;
1231 rd->ysch = isntsc ? 480 : 576;
1232 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1233 rd->ffcodecdata.rc_max_rate = 9000;
1234 rd->ffcodecdata.rc_min_rate = 0;
1235 rd->ffcodecdata.rc_buffer_size = 224*8;
1236 rd->ffcodecdata.mux_packet_size = 2048;
1237 rd->ffcodecdata.mux_rate = 10080000;
1240 case FFMPEG_PRESET_DV:
1241 rd->ffcodecdata.type = FFMPEG_DV;
1243 rd->ysch = isntsc ? 480 : 576;
1246 case FFMPEG_PRESET_H264:
1247 rd->ffcodecdata.type = FFMPEG_AVI;
1248 rd->ffcodecdata.codec = CODEC_ID_H264;
1249 rd->ffcodecdata.video_bitrate = 6000;
1250 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1251 rd->ffcodecdata.rc_max_rate = 9000;
1252 rd->ffcodecdata.rc_min_rate = 0;
1253 rd->ffcodecdata.rc_buffer_size = 224*8;
1254 rd->ffcodecdata.mux_packet_size = 2048;
1255 rd->ffcodecdata.mux_rate = 10080000;
1258 * All options here are for x264, but must be set via ffmpeg.
1259 * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1264 * Use CABAC coder. Using "coder:1", which should be equivalent,
1265 * crashes Blender for some reason. Either way - this is no big deal.
1267 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1270 * The other options were taken from the libx264-default.preset
1271 * included in the ffmpeg distribution.
1273 ffmpeg_property_add_string(rd, "video", "flags:loop");
1274 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1275 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1276 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1277 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1278 ffmpeg_property_add_string(rd, "video", "me:hex");
1279 ffmpeg_property_add_string(rd, "video", "subq:6");
1280 ffmpeg_property_add_string(rd, "video", "me_range:16");
1281 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1282 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1283 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1284 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1285 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1286 ffmpeg_property_add_string(rd, "video", "bf:3");
1287 ffmpeg_property_add_string(rd, "video", "refs:2");
1288 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1289 ffmpeg_property_add_string(rd, "video", "directpred:3");
1290 ffmpeg_property_add_string(rd, "video", "trellis:0");
1291 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1292 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1293 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1294 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1296 // This makes x264 output lossless. Will be a separate option later.
1297 //ffmpeg_property_add_string(rd, "video", "cqp:0");
1300 case FFMPEG_PRESET_THEORA:
1301 case FFMPEG_PRESET_XVID:
1302 if(preset == FFMPEG_PRESET_XVID) {
1303 rd->ffcodecdata.type = FFMPEG_AVI;
1304 rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1306 else if(preset == FFMPEG_PRESET_THEORA) {
1307 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1308 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1311 rd->ffcodecdata.video_bitrate = 6000;
1312 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1313 rd->ffcodecdata.rc_max_rate = 9000;
1314 rd->ffcodecdata.rc_min_rate = 0;
1315 rd->ffcodecdata.rc_buffer_size = 224*8;
1316 rd->ffcodecdata.mux_packet_size = 2048;
1317 rd->ffcodecdata.mux_rate = 10080000;
1323 void ffmpeg_verify_image_type(RenderData *rd)
1327 if(rd->imtype == R_FFMPEG) {
1328 if(rd->ffcodecdata.type <= 0 ||
1329 rd->ffcodecdata.codec <= 0 ||
1330 rd->ffcodecdata.audio_codec <= 0 ||
1331 rd->ffcodecdata.video_bitrate <= 1) {
1333 rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1334 /* Don't set preset, disturbs render resolution.
1335 * ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD); */
1340 else if(rd->imtype == R_H264) {
1341 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1342 ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1346 else if(rd->imtype == R_XVID) {
1347 if(rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1348 ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1352 else if(rd->imtype == R_THEORA) {
1353 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1354 ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1359 if(audio && rd->ffcodecdata.audio_codec < 0) {
1360 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1361 rd->ffcodecdata.audio_bitrate = 128;