4 * Partial Copyright (c) 2006 Peter Schlaile
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
22 #if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
23 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
31 #include <libavformat/avformat.h>
32 #include <libavcodec/avcodec.h>
33 #include <libavutil/rational.h>
34 #include <libswscale/swscale.h>
35 #include <libavcodec/opt.h>
37 #if LIBAVFORMAT_VERSION_INT < (49 << 16)
38 #define FFMPEG_OLD_FRAME_RATE 1
40 #define FFMPEG_CODEC_IS_POINTER 1
41 #define FFMPEG_CODEC_TIME_BASE 1
44 #if LIBAVFORMAT_VERSION_INT >= (52 << 16)
45 #define OUTFILE_PB (outfile->pb)
47 #define OUTFILE_PB (&outfile->pb)
50 #if defined(WIN32) && (!(defined snprintf))
51 #define snprintf _snprintf
54 #include "MEM_guardedalloc.h"
56 #include "DNA_scene_types.h"
58 #include "BLI_blenlib.h"
60 #include "AUD_C-API.h" /* must be before BKE_sound.h for define */
62 #include "BKE_global.h"
63 #include "BKE_idprop.h"
65 #include "BKE_report.h"
66 #include "BKE_sound.h"
67 #include "BKE_writeffmpeg.h"
69 #include "IMB_imbuf_types.h"
70 #include "IMB_imbuf.h"
72 extern void do_init_ffmpeg();
74 static int ffmpeg_type = 0;
75 static int ffmpeg_codec = CODEC_ID_MPEG4;
76 static int ffmpeg_audio_codec = CODEC_ID_NONE;
77 static int ffmpeg_video_bitrate = 1150;
78 static int ffmpeg_audio_bitrate = 128;
79 static int ffmpeg_gop_size = 12;
80 static int ffmpeg_autosplit = 0;
81 static int ffmpeg_autosplit_count = 0;
83 static AVFormatContext* outfile = 0;
84 static AVStream* video_stream = 0;
85 static AVStream* audio_stream = 0;
86 static AVFrame* current_frame = 0;
87 static struct SwsContext *img_convert_ctx = 0;
89 static uint8_t* video_buffer = 0;
90 static int video_buffersize = 0;
92 static uint8_t* audio_input_buffer = 0;
93 static int audio_input_samples = 0;
94 static uint8_t* audio_output_buffer = 0;
95 static int audio_outbuf_size = 0;
96 static double audio_time = 0.0f;
98 static AUD_Device* audio_mixdown_device = 0;
100 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
102 /* Delete a picture buffer */
104 static void delete_picture(AVFrame* f)
107 if (f->data[0]) MEM_freeN(f->data[0]);
112 #ifdef FFMPEG_CODEC_IS_POINTER
113 static AVCodecContext* get_codec_from_stream(AVStream* stream)
115 return stream->codec;
118 static AVCodecContext* get_codec_from_stream(AVStream* stream)
120 return &stream->codec;
124 static int write_audio_frame(void)
126 AVCodecContext* c = NULL;
129 c = get_codec_from_stream(audio_stream);
131 av_init_packet(&pkt);
134 AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
135 audio_time += (double) audio_input_samples / (double) c->sample_rate;
137 pkt.size = avcodec_encode_audio(c, audio_output_buffer,
139 (short*) audio_input_buffer);
143 // XXX error("Error writing audio packet");
147 pkt.data = audio_output_buffer;
149 if(c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
151 #ifdef FFMPEG_CODEC_TIME_BASE
152 pkt.pts = av_rescale_q(c->coded_frame->pts,
153 c->time_base, audio_stream->time_base);
155 pkt.pts = c->coded_frame->pts;
157 fprintf(stderr, "Audio Frame PTS: %d\n", (int)pkt.pts);
160 pkt.stream_index = audio_stream->index;
161 pkt.flags |= PKT_FLAG_KEY;
162 if (av_interleaved_write_frame(outfile, &pkt) != 0) {
163 fprintf(stderr, "Error writing audio packet!\n");
169 /* Allocate a temporary frame */
170 static AVFrame* alloc_picture(int pix_fmt, int width, int height)
176 /* allocate space for the struct */
177 f = avcodec_alloc_frame();
179 size = avpicture_get_size(pix_fmt, width, height);
180 /* allocate the actual picture buffer */
181 buf = MEM_mallocN(size, "AVFrame buffer");
186 avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
190 /* Get the correct file extensions for the requested format,
191 first is always desired guess_format parameter */
192 static const char** get_file_extensions(int format)
196 static const char * rv[] = { ".dv", NULL };
200 static const char * rv[] = { ".mpg", ".mpeg", NULL };
204 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
209 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
213 static const char * rv[] = { ".avi", NULL };
217 static const char * rv[] = { ".mov", NULL };
221 /* FIXME: avi for now... */
222 static const char * rv[] = { ".avi", NULL };
227 /* FIXME: avi for now... */
228 static const char * rv[] = { ".avi", NULL };
232 static const char * rv[] = { ".flv", NULL };
236 static const char * rv[] = { ".mkv", NULL };
240 static const char * rv[] = { ".ogg", ".ogv", NULL };
244 static const char * rv[] = { ".mp3", NULL };
248 static const char * rv[] = { ".wav", NULL };
256 /* Write a frame to the output file */
257 static int write_video_frame(RenderData *rd, AVFrame* frame, ReportList *reports)
261 AVCodecContext* c = get_codec_from_stream(video_stream);
262 #ifdef FFMPEG_CODEC_TIME_BASE
263 frame->pts = rd->cfra - rd->sfra;
265 if (rd->mode & R_FIELDS) {
266 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
269 outsize = avcodec_encode_video(c, video_buffer, video_buffersize,
273 av_init_packet(&packet);
275 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
276 #ifdef FFMPEG_CODEC_TIME_BASE
277 packet.pts = av_rescale_q(c->coded_frame->pts,
279 video_stream->time_base);
281 packet.pts = c->coded_frame->pts;
283 fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
285 fprintf(stderr, "Video Frame PTS: not set\n");
287 if (c->coded_frame->key_frame)
288 packet.flags |= PKT_FLAG_KEY;
289 packet.stream_index = video_stream->index;
290 packet.data = video_buffer;
291 packet.size = outsize;
292 ret = av_interleaved_write_frame(outfile, &packet);
299 BKE_report(reports, RPT_ERROR, "Error writing frame.");
305 /* read and encode a frame of audio from the buffer */
306 static AVFrame* generate_video_frame(uint8_t* pixels, ReportList *reports)
308 uint8_t* rendered_frame;
310 AVCodecContext* c = get_codec_from_stream(video_stream);
311 int width = c->width;
312 int height = c->height;
315 if (c->pix_fmt != PIX_FMT_BGR32) {
316 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
318 BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
322 rgb_frame = current_frame;
325 rendered_frame = pixels;
327 /* Do RGBA-conversion and flipping in one step depending
330 if (ENDIAN_ORDER == L_ENDIAN) {
332 for (y = 0; y < height; y++) {
333 uint8_t* target = rgb_frame->data[0]
334 + width * 4 * (height - y - 1);
335 uint8_t* src = rendered_frame + width * 4 * y;
336 uint8_t* end = src + width * 4;
349 for (y = 0; y < height; y++) {
350 uint8_t* target = rgb_frame->data[0]
351 + width * 4 * (height - y - 1);
352 uint8_t* src = rendered_frame + width * 4 * y;
353 uint8_t* end = src + width * 4;
366 if (c->pix_fmt != PIX_FMT_BGR32) {
367 sws_scale(img_convert_ctx, (const uint8_t * const*) rgb_frame->data,
368 rgb_frame->linesize, 0, c->height,
369 current_frame->data, current_frame->linesize);
370 delete_picture(rgb_frame);
372 return current_frame;
375 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
379 const AVOption * rv = NULL;
381 fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
383 BLI_strncpy(name, prop->name, sizeof(name));
385 param = strchr(name, ':');
393 fprintf(stderr, "%s.\n", IDP_String(prop));
394 rv = av_set_string(c, prop->name, IDP_String(prop));
397 fprintf(stderr, "%g.\n", IDP_Float(prop));
398 rv = av_set_double(c, prop->name, IDP_Float(prop));
401 fprintf(stderr, "%d.\n", IDP_Int(prop));
405 rv = av_set_string(c, name, param);
410 rv = av_set_int(c, prop->name, IDP_Int(prop));
416 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
421 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char * prop_name)
427 if (!rd->ffcodecdata.properties) {
431 prop = IDP_GetPropertyFromGroup(
432 rd->ffcodecdata.properties, (char*) prop_name);
437 iter = IDP_GetGroupIterator(prop);
439 while ((curr = IDP_GroupIterNext(iter)) != NULL) {
440 set_ffmpeg_property_option(c, curr);
444 /* prepare a video stream for the output file */
446 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
447 int rectx, int recty)
452 st = av_new_stream(of, 0);
453 if (!st) return NULL;
455 /* Set up the codec context */
457 c = get_codec_from_stream(st);
458 c->codec_id = codec_id;
459 c->codec_type = CODEC_TYPE_VIDEO;
462 /* Get some values from the current render settings */
467 #ifdef FFMPEG_CODEC_TIME_BASE
468 /* FIXME: Really bad hack (tm) for NTSC support */
469 if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
470 c->time_base.den = 2997;
471 c->time_base.num = 100;
472 } else if ((double) ((int) rd->frs_sec_base) ==
474 c->time_base.den = rd->frs_sec;
475 c->time_base.num = (int) rd->frs_sec_base;
477 c->time_base.den = rd->frs_sec * 100000;
478 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
481 /* FIXME: Really bad hack (tm) for NTSC support */
482 if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
483 c->frame_rate = 2997;
484 c->frame_rate_base = 100;
485 } else if ((double) ((int) rd->frs_sec_base) ==
487 c->frame_rate = rd->frs_sec;
488 c->frame_rate_base = rd->frs_sec_base;
490 c->frame_rate = rd->frs_sec * 100000;
491 c->frame_rate_base = ((double) rd->frs_sec_base)*100000;
495 c->gop_size = ffmpeg_gop_size;
496 c->bit_rate = ffmpeg_video_bitrate*1000;
497 c->rc_max_rate = rd->ffcodecdata.rc_max_rate*1000;
498 c->rc_min_rate = rd->ffcodecdata.rc_min_rate*1000;
499 c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
500 c->rc_initial_buffer_occupancy
501 = rd->ffcodecdata.rc_buffer_size*3/4;
502 c->rc_buffer_aggressivity = 1.0;
503 c->me_method = ME_EPZS;
505 codec = avcodec_find_encoder(c->codec_id);
506 if (!codec) return NULL;
508 /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
510 if (codec->pix_fmts) {
511 c->pix_fmt = codec->pix_fmts[0];
513 /* makes HuffYUV happy ... */
514 c->pix_fmt = PIX_FMT_YUV422P;
517 if (codec_id == CODEC_ID_XVID) {
519 c->pix_fmt = PIX_FMT_YUV420P;
520 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
523 if (codec_id == CODEC_ID_H264) {
524 /* correct wrong default ffmpeg param which crash x264 */
529 if ((of->oformat->flags & AVFMT_GLOBALHEADER)
530 // || !strcmp(of->oformat->name, "mp4")
531 // || !strcmp(of->oformat->name, "mov")
532 // || !strcmp(of->oformat->name, "3gp")
534 fprintf(stderr, "Using global header\n");
535 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
538 /* Determine whether we are encoding interlaced material or not */
539 if (rd->mode & R_FIELDS) {
540 fprintf(stderr, "Encoding interlaced video\n");
541 c->flags |= CODEC_FLAG_INTERLACED_DCT;
542 c->flags |= CODEC_FLAG_INTERLACED_ME;
545 /* xasp & yasp got float lately... */
547 st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
548 ((double) rd->xasp / (double) rd->yasp), 255);
550 set_ffmpeg_properties(rd, c, "video");
552 if (avcodec_open(c, codec) < 0) {
554 //XXX error("Couldn't initialize codec");
558 video_buffersize = 2000000;
559 video_buffer = (uint8_t*)MEM_mallocN(video_buffersize,
560 "FFMPEG video buffer");
562 current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
564 img_convert_ctx = sws_getContext(c->width, c->height,
573 /* Prepare an audio stream for the output file */
575 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of)
581 st = av_new_stream(of, 1);
582 if (!st) return NULL;
584 c = get_codec_from_stream(st);
585 c->codec_id = codec_id;
586 c->codec_type = CODEC_TYPE_AUDIO;
588 c->sample_rate = rd->ffcodecdata.audio_mixrate;
589 c->bit_rate = ffmpeg_audio_bitrate*1000;
590 c->sample_fmt = SAMPLE_FMT_S16;
592 codec = avcodec_find_encoder(c->codec_id);
594 //XXX error("Couldn't find a valid audio codec");
598 set_ffmpeg_properties(rd, c, "audio");
600 if (avcodec_open(c, codec) < 0) {
601 //XXX error("Couldn't initialize audio codec");
605 audio_outbuf_size = FF_MIN_BUFFER_SIZE;
607 if((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
608 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
611 audio_input_samples = c->frame_size;
612 if(c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
613 audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
616 audio_output_buffer = (uint8_t*)MEM_mallocN(
617 audio_outbuf_size, "FFMPEG audio encoder input buffer");
619 audio_input_buffer = (uint8_t*)MEM_mallocN(
620 audio_input_samples * c->channels * sizeof(int16_t),
621 "FFMPEG audio encoder output buffer");
627 /* essential functions -- start, append, end */
629 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
631 /* Handle to the output file */
637 ffmpeg_type = rd->ffcodecdata.type;
638 ffmpeg_codec = rd->ffcodecdata.codec;
639 ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
640 ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
641 ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
642 ffmpeg_gop_size = rd->ffcodecdata.gop_size;
643 ffmpeg_autosplit = rd->ffcodecdata.flags
644 & FFMPEG_AUTOSPLIT_OUTPUT;
648 /* Determine the correct filename */
649 filepath_ffmpeg(name, rd);
650 fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
651 " Using type=%d, codec=%d, audio_codec=%d,\n"
652 " video_bitrate=%d, audio_bitrate=%d,\n"
653 " gop_size=%d, autosplit=%d\n"
654 " render width=%d, render height=%d\n",
655 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
656 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
657 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
659 exts = get_file_extensions(ffmpeg_type);
661 BKE_report(reports, RPT_ERROR, "No valid formats found.");
664 fmt = guess_format(NULL, exts[0], NULL);
666 BKE_report(reports, RPT_ERROR, "No valid formats found.");
670 of = av_alloc_format_context();
672 BKE_report(reports, RPT_ERROR, "Error opening output file");
677 of->packet_size= rd->ffcodecdata.mux_packet_size;
678 if (ffmpeg_audio_codec != CODEC_ID_NONE) {
679 of->mux_rate = rd->ffcodecdata.mux_rate;
684 of->preload = (int)(0.5*AV_TIME_BASE);
685 of->max_delay = (int)(0.7*AV_TIME_BASE);
687 fmt->audio_codec = ffmpeg_audio_codec;
689 snprintf(of->filename, sizeof(of->filename), "%s", name);
690 /* set the codec to the user's selection */
691 switch(ffmpeg_type) {
696 fmt->video_codec = ffmpeg_codec;
699 fmt->video_codec = CODEC_ID_DVVIDEO;
702 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
705 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
708 fmt->video_codec = CODEC_ID_H264;
711 fmt->video_codec = CODEC_ID_XVID;
714 fmt->video_codec = CODEC_ID_FLV1;
717 fmt->audio_codec = CODEC_ID_MP3;
719 fmt->video_codec = CODEC_ID_NONE;
723 fmt->video_codec = CODEC_ID_MPEG4;
726 if (fmt->video_codec == CODEC_ID_DVVIDEO) {
728 BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
731 if (rd->frs_sec != 25 && recty != 480) {
732 BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
735 if (rd->frs_sec == 25 && recty != 576) {
736 BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
741 if (ffmpeg_type == FFMPEG_DV) {
742 fmt->audio_codec = CODEC_ID_PCM_S16LE;
743 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000) {
744 BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
749 if (fmt->video_codec != CODEC_ID_NONE) {
750 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
751 printf("alloc video stream %p\n", video_stream);
753 BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
758 if (ffmpeg_audio_codec != CODEC_ID_NONE) {
759 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
761 BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
765 if (av_set_parameters(of, NULL) < 0) {
766 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
769 if (!(fmt->flags & AVFMT_NOFILE)) {
770 if (url_fopen(&of->pb, name, URL_WRONLY) < 0) {
771 BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
778 dump_format(of, 0, name, 1);
784 * Writes any delayed frames in the encoder. This function is called before
785 * closing the encoder.
788 * Since an encoder may use both past and future frames to predict
789 * inter-frames (H.264 B-frames, for example), it can output the frames
790 * in a different order from the one it was given.
791 * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
792 * them in the order 1, 4, 2, 3 - first the two frames used for predition,
793 * and then the bidirectionally-predicted frames. What this means in practice
794 * is that the encoder may not immediately produce one output frame for each
795 * input frame. These delayed frames must be flushed before we close the
796 * stream. We do this by calling avcodec_encode_video with NULL for the last
800 void flush_ffmpeg(void)
805 AVCodecContext* c = get_codec_from_stream(video_stream);
806 /* get the delayed frames */
809 av_init_packet(&packet);
811 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
813 fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
819 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
820 #ifdef FFMPEG_CODEC_TIME_BASE
821 packet.pts = av_rescale_q(c->coded_frame->pts,
823 video_stream->time_base);
825 packet.pts = c->coded_frame->pts;
827 fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
829 fprintf(stderr, "Video Frame PTS: not set\n");
831 if (c->coded_frame->key_frame) {
832 packet.flags |= PKT_FLAG_KEY;
834 packet.stream_index = video_stream->index;
835 packet.data = video_buffer;
836 packet.size = outsize;
837 ret = av_interleaved_write_frame(outfile, &packet);
839 fprintf(stderr, "Error writing delayed frame %d\n", ret);
843 avcodec_flush_buffers(get_codec_from_stream(video_stream));
846 /* **********************************************************************
848 ********************************************************************** */
850 /* Get the output filename-- similar to the other output formats */
851 void filepath_ffmpeg(char* string, RenderData* rd) {
854 const char ** exts = get_file_extensions(rd->ffcodecdata.type);
855 const char ** fe = exts;
857 if (!string || !exts) return;
859 strcpy(string, rd->pic);
860 BLI_path_abs(string, G.main->name);
862 BLI_make_existing_file(string);
866 if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
867 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
871 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe),
879 strcat(string, autosplit);
881 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
882 strcat(string, *exts);
884 *(string + strlen(string) - strlen(*fe)) = 0;
885 strcat(string, autosplit);
890 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
894 ffmpeg_autosplit_count = 0;
896 success = start_ffmpeg_impl(rd, rectx, recty, reports);
900 AVCodecContext* c = get_codec_from_stream(audio_stream);
901 AUD_DeviceSpecs specs;
902 specs.channels = c->channels;
903 specs.format = AUD_FORMAT_S16;
904 specs.rate = rd->ffcodecdata.audio_mixrate;
905 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
911 void end_ffmpeg(void);
913 static void write_audio_frames(double to_pts)
917 while (audio_stream && !finished) {
918 if((audio_time >= to_pts) ||
919 (write_audio_frame())) {
925 int append_ffmpeg(RenderData *rd, int frame, int *pixels, int rectx, int recty, ReportList *reports)
930 fprintf(stderr, "Writing frame %i, "
931 "render width=%d, render height=%d\n", frame,
934 // why is this done before writing the video frame and again at end_ffmpeg?
935 // write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
939 avframe= generate_video_frame((unsigned char*) pixels, reports);
940 success= (avframe && write_video_frame(rd, avframe, reports));
942 if (ffmpeg_autosplit) {
943 if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
945 ffmpeg_autosplit_count++;
946 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
951 write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
956 void end_ffmpeg(void)
960 fprintf(stderr, "Closing ffmpeg...\n");
962 /* if (audio_stream) { SEE UPPER
963 write_audio_frames();
966 if(audio_mixdown_device)
968 AUD_closeReadDevice(audio_mixdown_device);
969 audio_mixdown_device = 0;
972 if (video_stream && get_codec_from_stream(video_stream)) {
973 fprintf(stderr, "Flushing delayed frames...\n");
978 av_write_trailer(outfile);
981 /* Close the video codec */
983 if (video_stream && get_codec_from_stream(video_stream)) {
984 avcodec_close(get_codec_from_stream(video_stream));
985 printf("zero video stream %p\n", video_stream);
990 /* Close the output file */
992 for (i = 0; i < outfile->nb_streams; i++) {
993 if (&outfile->streams[i]) {
994 av_freep(&outfile->streams[i]);
998 /* free the temp buffer */
1000 delete_picture(current_frame);
1003 if (outfile && outfile->oformat) {
1004 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1005 url_fclose(OUTFILE_PB);
1013 MEM_freeN(video_buffer);
1016 if (audio_output_buffer) {
1017 MEM_freeN(audio_output_buffer);
1018 audio_output_buffer = 0;
1020 if (audio_input_buffer) {
1021 MEM_freeN(audio_input_buffer);
1022 audio_input_buffer = 0;
1025 if (img_convert_ctx) {
1026 sws_freeContext(img_convert_ctx);
1027 img_convert_ctx = 0;
1033 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1035 struct IDProperty *prop = (struct IDProperty *) prop_;
1038 if (!rd->ffcodecdata.properties) {
1042 group = IDP_GetPropertyFromGroup(
1043 rd->ffcodecdata.properties, (char*) type);
1044 if (group && prop) {
1045 IDP_RemFromGroup(group, prop);
1046 IDP_FreeProperty(prop);
1051 IDProperty *ffmpeg_property_add(RenderData *rd, char * type, int opt_index, int parent_index)
1055 const AVOption * parent;
1058 IDPropertyTemplate val;
1064 avcodec_get_context_defaults(&c);
1066 o = c.av_class->option + opt_index;
1067 parent = c.av_class->option + parent_index;
1069 if (!rd->ffcodecdata.properties) {
1070 rd->ffcodecdata.properties
1071 = IDP_New(IDP_GROUP, val, "ffmpeg");
1074 group = IDP_GetPropertyFromGroup(
1075 rd->ffcodecdata.properties, (char*) type);
1078 group = IDP_New(IDP_GROUP, val, (char*) type);
1079 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1083 sprintf(name, "%s:%s", parent->name, o->name);
1085 strcpy(name, o->name);
1088 fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1089 type, parent_index, opt_index, name);
1091 prop = IDP_GetPropertyFromGroup(group, name);
1097 case FF_OPT_TYPE_INT:
1098 case FF_OPT_TYPE_INT64:
1099 val.i = o->default_val;
1102 case FF_OPT_TYPE_DOUBLE:
1103 case FF_OPT_TYPE_FLOAT:
1104 val.f = o->default_val;
1105 idp_type = IDP_FLOAT;
1107 case FF_OPT_TYPE_STRING:
1109 idp_type = IDP_STRING;
1111 case FF_OPT_TYPE_CONST:
1118 prop = IDP_New(idp_type, val, name);
1119 IDP_AddToGroup(group, prop);
1123 /* not all versions of ffmpeg include that, so here we go ... */
1125 static const AVOption *my_av_find_opt(void *v, const char *name,
1126 const char *unit, int mask, int flags){
1127 AVClass *c= *(AVClass**)v;
1128 const AVOption *o= c->option;
1130 for(;o && o->name; o++){
1131 if(!strcmp(o->name, name) &&
1132 (!unit || (o->unit && !strcmp(o->unit, unit))) &&
1133 (o->flags & mask) == flags )
1139 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1142 const AVOption * o = 0;
1143 const AVOption * p = 0;
1149 avcodec_get_context_defaults(&c);
1151 strncpy(name_, str, sizeof(name_));
1154 while (*name == ' ') name++;
1156 param = strchr(name, ':');
1159 param = strchr(name, ' ');
1163 while (*param == ' ') param++;
1166 o = my_av_find_opt(&c, name, NULL, 0, 0);
1170 if (param && o->type == FF_OPT_TYPE_CONST) {
1173 if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1174 p = my_av_find_opt(&c, param, o->unit, 0, 0);
1175 prop = ffmpeg_property_add(rd,
1176 (char*) type, p - c.av_class->option,
1177 o - c.av_class->option);
1179 prop = ffmpeg_property_add(rd,
1180 (char*) type, o - c.av_class->option, 0);
1189 switch (prop->type) {
1191 IDP_Int(prop) = atoi(param);
1194 IDP_Float(prop) = atof(param);
1197 strncpy(IDP_String(prop), param, prop->len);
1204 void ffmpeg_set_preset(RenderData *rd, int preset)
1206 int isntsc = (rd->frs_sec != 25);
1209 case FFMPEG_PRESET_VCD:
1210 rd->ffcodecdata.type = FFMPEG_MPEG1;
1211 rd->ffcodecdata.video_bitrate = 1150;
1213 rd->ysch = isntsc ? 240 : 288;
1214 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1215 rd->ffcodecdata.rc_max_rate = 1150;
1216 rd->ffcodecdata.rc_min_rate = 1150;
1217 rd->ffcodecdata.rc_buffer_size = 40*8;
1218 rd->ffcodecdata.mux_packet_size = 2324;
1219 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1222 case FFMPEG_PRESET_SVCD:
1223 rd->ffcodecdata.type = FFMPEG_MPEG2;
1224 rd->ffcodecdata.video_bitrate = 2040;
1226 rd->ysch = isntsc ? 480 : 576;
1227 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1228 rd->ffcodecdata.rc_max_rate = 2516;
1229 rd->ffcodecdata.rc_min_rate = 0;
1230 rd->ffcodecdata.rc_buffer_size = 224*8;
1231 rd->ffcodecdata.mux_packet_size = 2324;
1232 rd->ffcodecdata.mux_rate = 0;
1235 case FFMPEG_PRESET_DVD:
1236 rd->ffcodecdata.type = FFMPEG_MPEG2;
1237 rd->ffcodecdata.video_bitrate = 6000;
1239 rd->ysch = isntsc ? 480 : 576;
1240 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1241 rd->ffcodecdata.rc_max_rate = 9000;
1242 rd->ffcodecdata.rc_min_rate = 0;
1243 rd->ffcodecdata.rc_buffer_size = 224*8;
1244 rd->ffcodecdata.mux_packet_size = 2048;
1245 rd->ffcodecdata.mux_rate = 10080000;
1248 case FFMPEG_PRESET_DV:
1249 rd->ffcodecdata.type = FFMPEG_DV;
1251 rd->ysch = isntsc ? 480 : 576;
1254 case FFMPEG_PRESET_H264:
1255 rd->ffcodecdata.type = FFMPEG_AVI;
1256 rd->ffcodecdata.codec = CODEC_ID_H264;
1257 rd->ffcodecdata.video_bitrate = 6000;
1258 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1259 rd->ffcodecdata.rc_max_rate = 9000;
1260 rd->ffcodecdata.rc_min_rate = 0;
1261 rd->ffcodecdata.rc_buffer_size = 224*8;
1262 rd->ffcodecdata.mux_packet_size = 2048;
1263 rd->ffcodecdata.mux_rate = 10080000;
1266 * All options here are for x264, but must be set via ffmpeg.
1267 * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1272 * Use CABAC coder. Using "coder:1", which should be equivalent,
1273 * crashes Blender for some reason. Either way - this is no big deal.
1275 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1278 * The other options were taken from the libx264-default.preset
1279 * included in the ffmpeg distribution.
1281 ffmpeg_property_add_string(rd, "video", "flags:loop");
1282 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1283 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1284 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1285 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1286 ffmpeg_property_add_string(rd, "video", "me:hex");
1287 ffmpeg_property_add_string(rd, "video", "subq:6");
1288 ffmpeg_property_add_string(rd, "video", "me_range:16");
1289 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1290 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1291 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1292 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1293 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1294 ffmpeg_property_add_string(rd, "video", "bf:3");
1295 ffmpeg_property_add_string(rd, "video", "refs:2");
1296 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1297 ffmpeg_property_add_string(rd, "video", "directpred:3");
1298 ffmpeg_property_add_string(rd, "video", "trellis:0");
1299 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1300 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1301 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1302 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1304 // This makes x264 output lossless. Will be a separate option later.
1305 //ffmpeg_property_add_string(rd, "video", "cqp:0");
1308 case FFMPEG_PRESET_THEORA:
1309 case FFMPEG_PRESET_XVID:
1310 if(preset == FFMPEG_PRESET_XVID) {
1311 rd->ffcodecdata.type = FFMPEG_AVI;
1312 rd->ffcodecdata.codec = CODEC_ID_XVID;
1314 else if(preset == FFMPEG_PRESET_THEORA) {
1315 rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1316 rd->ffcodecdata.codec = CODEC_ID_THEORA;
1319 rd->ffcodecdata.video_bitrate = 6000;
1320 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1321 rd->ffcodecdata.rc_max_rate = 9000;
1322 rd->ffcodecdata.rc_min_rate = 0;
1323 rd->ffcodecdata.rc_buffer_size = 224*8;
1324 rd->ffcodecdata.mux_packet_size = 2048;
1325 rd->ffcodecdata.mux_rate = 10080000;
1331 void ffmpeg_verify_image_type(RenderData *rd)
1335 if(rd->imtype == R_FFMPEG) {
1336 if(rd->ffcodecdata.type <= 0 ||
1337 rd->ffcodecdata.codec <= 0 ||
1338 rd->ffcodecdata.audio_codec <= 0 ||
1339 rd->ffcodecdata.video_bitrate <= 1) {
1341 rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1342 /* Don't set preset, disturbs render resolution.
1343 * ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD); */
1348 else if(rd->imtype == R_H264) {
1349 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1350 ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1354 else if(rd->imtype == R_XVID) {
1355 if(rd->ffcodecdata.codec != CODEC_ID_XVID) {
1356 ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1360 else if(rd->imtype == R_THEORA) {
1361 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1362 ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1367 if(audio && rd->ffcodecdata.audio_codec < 0) {
1368 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1369 rd->ffcodecdata.audio_bitrate = 128;