Fix: [#24006] writeffmpeg doesn't flush delayed frames - fix attached
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  * ffmpeg-write support
3  *
4  * Partial Copyright (c) 2006 Peter Schlaile
5  *
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.
10  *
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.
15  *
16  */
17
18 #ifdef WITH_FFMPEG
19 #include <string.h>
20 #include <stdio.h>
21
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? */
24 #if _MSC_VER < 1400
25 #include <stdint.h>
26 #endif
27 #endif
28
29 #include <stdlib.h>
30
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>
36
37 #if LIBAVFORMAT_VERSION_INT < (49 << 16)
38 #define FFMPEG_OLD_FRAME_RATE 1
39 #else
40 #define FFMPEG_CODEC_IS_POINTER 1
41 #define FFMPEG_CODEC_TIME_BASE  1
42 #endif
43
44 #if LIBAVFORMAT_VERSION_INT >= (52 << 16)
45 #define OUTFILE_PB (outfile->pb)
46 #else
47 #define OUTFILE_PB (&outfile->pb)
48 #endif
49
50 #if defined(WIN32) && (!(defined snprintf))
51 #define snprintf _snprintf
52 #endif
53
54 #include "MEM_guardedalloc.h"
55
56 #include "DNA_scene_types.h"
57
58 #include "BLI_blenlib.h"
59
60 #include "AUD_C-API.h" /* must be before BKE_sound.h for define */
61
62 #include "BKE_global.h"
63 #include "BKE_idprop.h"
64 #include "BKE_main.h"
65 #include "BKE_report.h"
66 #include "BKE_sound.h"
67 #include "BKE_writeffmpeg.h"
68
69 #include "IMB_imbuf_types.h"
70 #include "IMB_imbuf.h"
71
72 extern void do_init_ffmpeg();
73
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;
82
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;
88
89 static uint8_t* video_buffer = 0;
90 static int video_buffersize = 0;
91
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;
97
98 static AUD_Device* audio_mixdown_device = 0;
99
100 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
101
102 /* Delete a picture buffer */
103
104 static void delete_picture(AVFrame* f)
105 {
106         if (f) {
107                 if (f->data[0]) MEM_freeN(f->data[0]);
108                 av_free(f);
109         }
110 }
111
112 #ifdef FFMPEG_CODEC_IS_POINTER
113 static AVCodecContext* get_codec_from_stream(AVStream* stream)
114 {
115         return stream->codec;
116 }
117 #else
118 static AVCodecContext* get_codec_from_stream(AVStream* stream)
119 {
120         return &stream->codec;
121 }
122 #endif
123
124 static int write_audio_frame(void) 
125 {
126         AVCodecContext* c = NULL;
127         AVPacket pkt;
128
129         c = get_codec_from_stream(audio_stream);
130
131         av_init_packet(&pkt);
132         pkt.size = 0;
133
134         AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
135         audio_time += (double) audio_input_samples / (double) c->sample_rate;
136
137         pkt.size = avcodec_encode_audio(c, audio_output_buffer,
138                                         audio_outbuf_size,
139                                         (short*) audio_input_buffer);
140
141         if(pkt.size < 0)
142         {
143                 // XXX error("Error writing audio packet");
144                 return -1;
145         }
146
147         pkt.data = audio_output_buffer;
148
149         if(c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE)
150         {
151 #ifdef FFMPEG_CODEC_TIME_BASE
152                 pkt.pts = av_rescale_q(c->coded_frame->pts,
153                                            c->time_base, audio_stream->time_base);
154 #else
155                 pkt.pts = c->coded_frame->pts;
156 #endif
157                 fprintf(stderr, "Audio Frame PTS: %d\n", (int)pkt.pts);
158         }
159
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");
164                 return -1;
165         }
166         return 0;
167 }
168
169 /* Allocate a temporary frame */
170 static AVFrame* alloc_picture(int pix_fmt, int width, int height) 
171 {
172         AVFrame* f;
173         uint8_t* buf;
174         int size;
175         
176         /* allocate space for the struct */
177         f = avcodec_alloc_frame();
178         if (!f) return NULL;
179         size = avpicture_get_size(pix_fmt, width, height);
180         /* allocate the actual picture buffer */
181         buf = MEM_mallocN(size, "AVFrame buffer");
182         if (!buf) {
183                 free(f);
184                 return NULL;
185         }
186         avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
187         return f;
188 }
189
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) 
193 {
194         switch(format) {
195         case FFMPEG_DV: {
196                 static const char * rv[] = { ".dv", NULL };
197                 return rv;
198         }
199         case FFMPEG_MPEG1: {
200                 static const char * rv[] = { ".mpg", ".mpeg", NULL };
201                 return rv;
202         }
203         case FFMPEG_MPEG2: {
204                 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
205                                                  NULL };
206                 return rv;
207         }
208         case FFMPEG_MPEG4: {
209                 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
210                 return rv;
211         }
212         case FFMPEG_AVI: {
213                 static const char * rv[] = { ".avi", NULL };
214                 return rv;
215         }
216         case FFMPEG_MOV: {
217                 static const char * rv[] = { ".mov", NULL };
218                 return rv;
219         }
220         case FFMPEG_H264: {
221                 /* FIXME: avi for now... */
222                 static const char * rv[] = { ".avi", NULL };
223                 return rv;
224         }
225
226         case FFMPEG_XVID: {
227                 /* FIXME: avi for now... */
228                 static const char * rv[] = { ".avi", NULL };
229                 return rv;
230         }
231         case FFMPEG_FLV: {
232                 static const char * rv[] = { ".flv", NULL };
233                 return rv;
234         }
235         case FFMPEG_MKV: {
236                 static const char * rv[] = { ".mkv", NULL };
237                 return rv;
238         }
239         case FFMPEG_OGG: {
240                 static const char * rv[] = { ".ogg", ".ogv", NULL };
241                 return rv;
242         }
243         case FFMPEG_MP3: {
244                 static const char * rv[] = { ".mp3", NULL };
245                 return rv;
246         }
247         case FFMPEG_WAV: {
248                 static const char * rv[] = { ".wav", NULL };
249                 return rv;
250         }
251         default:
252                 return NULL;
253         }
254 }
255
256 /* Write a frame to the output file */
257 static int write_video_frame(RenderData *rd, AVFrame* frame, ReportList *reports)
258 {
259         int outsize = 0;
260         int ret, success= 1;
261         AVCodecContext* c = get_codec_from_stream(video_stream);
262 #ifdef FFMPEG_CODEC_TIME_BASE
263         frame->pts = rd->cfra - rd->sfra;
264 #endif
265         if (rd->mode & R_FIELDS) {
266                 frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
267         }
268
269         outsize = avcodec_encode_video(c, video_buffer, video_buffersize, 
270                                            frame);
271         if (outsize != 0) {
272                 AVPacket packet;
273                 av_init_packet(&packet);
274
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,
278                                                   c->time_base,
279                                                   video_stream->time_base);
280 #else
281                         packet.pts = c->coded_frame->pts;
282 #endif
283                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
284                 } else {
285                         fprintf(stderr, "Video Frame PTS: not set\n");
286                 }
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);
293         } else {
294                 ret = 0;
295         }
296
297         if (ret != 0) {
298                 success= 0;
299                 BKE_report(reports, RPT_ERROR, "Error writing frame.");
300         }
301
302         return success;
303 }
304
305 /* read and encode a frame of audio from the buffer */
306 static AVFrame* generate_video_frame(uint8_t* pixels, ReportList *reports) 
307 {
308         uint8_t* rendered_frame;
309
310         AVCodecContext* c = get_codec_from_stream(video_stream);
311         int width = c->width;
312         int height = c->height;
313         AVFrame* rgb_frame;
314
315         if (c->pix_fmt != PIX_FMT_BGR32) {
316                 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
317                 if (!rgb_frame) {
318                         BKE_report(reports, RPT_ERROR, "Couldn't allocate temporary frame.");
319                         return NULL;
320                 }
321         } else {
322                 rgb_frame = current_frame;
323         }
324
325         rendered_frame = pixels;
326
327         /* Do RGBA-conversion and flipping in one step depending
328            on CPU-Endianess */
329
330         if (ENDIAN_ORDER == L_ENDIAN) {
331                 int y;
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;
337                         while (src != end) {
338                                 target[3] = src[3];
339                                 target[2] = src[2];
340                                 target[1] = src[1];
341                                 target[0] = src[0];
342
343                                 target += 4;
344                                 src += 4;
345                         }
346                 }
347         } else {
348                 int y;
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;
354                         while (src != end) {
355                                 target[3] = src[0];
356                                 target[2] = src[1];
357                                 target[1] = src[2];
358                                 target[0] = src[3];
359
360                                 target += 4;
361                                 src += 4;
362                         }
363                 }
364         }
365
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);
371         }
372         return current_frame;
373 }
374
375 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
376 {
377         char name[128];
378         char * param;
379         const AVOption * rv = NULL;
380
381         fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
382
383         BLI_strncpy(name, prop->name, sizeof(name));
384
385         param = strchr(name, ':');
386
387         if (param) {
388                 *param++ = 0;
389         }
390
391         switch(prop->type) {
392         case IDP_STRING:
393                 fprintf(stderr, "%s.\n", IDP_String(prop));
394                 rv = av_set_string(c, prop->name, IDP_String(prop));
395                 break;
396         case IDP_FLOAT:
397                 fprintf(stderr, "%g.\n", IDP_Float(prop));
398                 rv = av_set_double(c, prop->name, IDP_Float(prop));
399                 break;
400         case IDP_INT:
401                 fprintf(stderr, "%d.\n", IDP_Int(prop));
402                 
403                 if (param) {
404                         if (IDP_Int(prop)) {
405                                 rv = av_set_string(c, name, param);
406                         } else {
407                                 return;
408                         }
409                 } else {
410                         rv = av_set_int(c, prop->name, IDP_Int(prop));
411                 }
412                 break;
413         }
414
415         if (!rv) {
416                 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
417                         prop->name);
418         }
419 }
420
421 static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char * prop_name)
422 {
423         IDProperty * prop;
424         void * iter;
425         IDProperty * curr;
426
427         if (!rd->ffcodecdata.properties) {
428                 return;
429         }
430         
431         prop = IDP_GetPropertyFromGroup(
432                 rd->ffcodecdata.properties, (char*) prop_name);
433         if (!prop) {
434                 return;
435         }
436
437         iter = IDP_GetGroupIterator(prop);
438
439         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
440                 set_ffmpeg_property_option(c, curr);
441         }
442 }
443
444 /* prepare a video stream for the output file */
445
446 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
447                                         int rectx, int recty) 
448 {
449         AVStream* st;
450         AVCodecContext* c;
451         AVCodec* codec;
452         st = av_new_stream(of, 0);
453         if (!st) return NULL;
454
455         /* Set up the codec context */
456         
457         c = get_codec_from_stream(st);
458         c->codec_id = codec_id;
459         c->codec_type = CODEC_TYPE_VIDEO;
460
461
462         /* Get some values from the current render settings */
463         
464         c->width = rectx;
465         c->height = recty;
466
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) == 
473                    rd->frs_sec_base) {
474                 c->time_base.den = rd->frs_sec;
475                 c->time_base.num = (int) rd->frs_sec_base;
476         } else {
477                 c->time_base.den = rd->frs_sec * 100000;
478                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
479         }
480 #else
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) == 
486                    rd->frs_sec_base) {
487                 c->frame_rate = rd->frs_sec;
488                 c->frame_rate_base = rd->frs_sec_base;
489         } else {
490                 c->frame_rate = rd->frs_sec * 100000;
491                 c->frame_rate_base = ((double) rd->frs_sec_base)*100000;
492         }
493 #endif
494         
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;
504         
505         codec = avcodec_find_encoder(c->codec_id);
506         if (!codec) return NULL;
507         
508         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
509         
510         if (codec->pix_fmts) {
511                 c->pix_fmt = codec->pix_fmts[0];
512         } else {
513                 /* makes HuffYUV happy ... */
514                 c->pix_fmt = PIX_FMT_YUV422P;
515         }
516
517         if (codec_id == CODEC_ID_XVID) {
518                 /* arghhhh ... */
519                 c->pix_fmt = PIX_FMT_YUV420P;
520                 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
521         }
522
523         if (codec_id == CODEC_ID_H264) {
524                 /* correct wrong default ffmpeg param which crash x264 */
525                 c->qmin=10;
526                 c->qmax=51;
527         }
528         
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")
533                 ) {
534                 fprintf(stderr, "Using global header\n");
535                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
536         }
537         
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;
543         }
544
545         /* xasp & yasp got float lately... */
546
547         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
548                 ((double) rd->xasp / (double) rd->yasp), 255);
549
550         set_ffmpeg_properties(rd, c, "video");
551         
552         if (avcodec_open(c, codec) < 0) {
553                 //
554                 //XXX error("Couldn't initialize codec");
555                 return NULL;
556         }
557
558         video_buffersize = 2000000;
559         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize, 
560                                                  "FFMPEG video buffer");
561         
562         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
563
564         img_convert_ctx = sws_getContext(c->width, c->height,
565                                          PIX_FMT_BGR32,
566                                          c->width, c->height,
567                                          c->pix_fmt,
568                                          SWS_BICUBIC,
569                                          NULL, NULL, NULL);
570         return st;
571 }
572
573 /* Prepare an audio stream for the output file */
574
575 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of) 
576 {
577         AVStream* st;
578         AVCodecContext* c;
579         AVCodec* codec;
580
581         st = av_new_stream(of, 1);
582         if (!st) return NULL;
583
584         c = get_codec_from_stream(st);
585         c->codec_id = codec_id;
586         c->codec_type = CODEC_TYPE_AUDIO;
587
588         c->sample_rate = rd->ffcodecdata.audio_mixrate;
589         c->bit_rate = ffmpeg_audio_bitrate*1000;
590         c->sample_fmt = SAMPLE_FMT_S16;
591         c->channels = 2;
592         codec = avcodec_find_encoder(c->codec_id);
593         if (!codec) {
594                 //XXX error("Couldn't find a valid audio codec");
595                 return NULL;
596         }
597
598         set_ffmpeg_properties(rd, c, "audio");
599
600         if (avcodec_open(c, codec) < 0) {
601                 //XXX error("Couldn't initialize audio codec");
602                 return NULL;
603         }
604
605         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
606
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;
609         else
610         {
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;
614         }
615
616         audio_output_buffer = (uint8_t*)MEM_mallocN(
617                 audio_outbuf_size, "FFMPEG audio encoder input buffer");
618
619         audio_input_buffer = (uint8_t*)MEM_mallocN(
620                 audio_input_samples * c->channels * sizeof(int16_t),
621                 "FFMPEG audio encoder output buffer");
622
623         audio_time = 0.0f;
624
625         return st;
626 }
627 /* essential functions -- start, append, end */
628
629 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
630 {
631         /* Handle to the output file */
632         AVFormatContext* of;
633         AVOutputFormat* fmt;
634         char name[256];
635         const char ** exts;
636
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;
645         
646         do_init_ffmpeg();
647
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);
658         
659         exts = get_file_extensions(ffmpeg_type);
660         if (!exts) {
661                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
662                 return 0;
663         }
664         fmt = guess_format(NULL, exts[0], NULL);
665         if (!fmt) {
666                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
667                 return 0;
668         }
669
670         of = av_alloc_format_context();
671         if (!of) {
672                 BKE_report(reports, RPT_ERROR, "Error opening output file");
673                 return 0;
674         }
675         
676         of->oformat = fmt;
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;
680         } else {
681                 of->mux_rate = 0;
682         }
683
684         of->preload = (int)(0.5*AV_TIME_BASE);
685         of->max_delay = (int)(0.7*AV_TIME_BASE);
686
687         fmt->audio_codec = ffmpeg_audio_codec;
688
689         snprintf(of->filename, sizeof(of->filename), "%s", name);
690         /* set the codec to the user's selection */
691         switch(ffmpeg_type) {
692         case FFMPEG_AVI:
693         case FFMPEG_MOV:
694         case FFMPEG_OGG:
695         case FFMPEG_MKV:
696                 fmt->video_codec = ffmpeg_codec;
697                 break;
698         case FFMPEG_DV:
699                 fmt->video_codec = CODEC_ID_DVVIDEO;
700                 break;
701         case FFMPEG_MPEG1:
702                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
703                 break;
704         case FFMPEG_MPEG2:
705                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
706                 break;
707         case FFMPEG_H264:
708                 fmt->video_codec = CODEC_ID_H264;
709                 break;
710         case FFMPEG_XVID:
711                 fmt->video_codec = CODEC_ID_XVID;
712                 break;
713         case FFMPEG_FLV:
714                 fmt->video_codec = CODEC_ID_FLV1;
715                 break;
716         case FFMPEG_MP3:
717                 fmt->audio_codec = CODEC_ID_MP3;
718         case FFMPEG_WAV:
719                 fmt->video_codec = CODEC_ID_NONE;
720                 break;
721         case FFMPEG_MPEG4:
722         default:
723                 fmt->video_codec = CODEC_ID_MPEG4;
724                 break;
725         }
726         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
727                 if (rectx != 720) {
728                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
729                         return 0;
730                 }
731                 if (rd->frs_sec != 25 && recty != 480) {
732                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
733                         return 0;
734                 }
735                 if (rd->frs_sec == 25 && recty != 576) {
736                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
737                         return 0;
738                 }
739         }
740         
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!");
745                         return 0;
746                 }
747         }
748         
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);
752                 if (!video_stream) {
753                         BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
754                         return 0;
755                 }
756         }
757
758         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
759                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
760                 if (!audio_stream) {
761                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
762                         return 0;
763                 }
764         }
765         if (av_set_parameters(of, NULL) < 0) {
766                 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
767                 return 0;
768         }
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.");
772                         return 0;
773                 }
774         }
775
776         av_write_header(of);
777         outfile = of;
778         dump_format(of, 0, name, 1);
779
780         return 1;
781 }
782
783 /**
784  * Writes any delayed frames in the encoder. This function is called before 
785  * closing the encoder.
786  *
787  * <p>
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 
797  * parameter.
798  * </p>
799  */
800 void flush_ffmpeg(void)
801 {
802         int outsize = 0;
803         int ret = 0;
804         
805         AVCodecContext* c = get_codec_from_stream(video_stream);
806         /* get the delayed frames */
807         while (1) {
808                 AVPacket packet;
809                 av_init_packet(&packet);
810                 
811                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
812                 if (outsize < 0) {
813                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
814                         break;
815                 }
816                 if (outsize == 0) {
817                         break;
818                 }
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,
822                                                   c->time_base,
823                                                   video_stream->time_base);
824 #else
825                         packet.pts = c->coded_frame->pts;
826 #endif
827                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
828                 } else {
829                         fprintf(stderr, "Video Frame PTS: not set\n");
830                 }
831                 if (c->coded_frame->key_frame) {
832                         packet.flags |= PKT_FLAG_KEY;
833                 }
834                 packet.stream_index = video_stream->index;
835                 packet.data = video_buffer;
836                 packet.size = outsize;
837                 ret = av_interleaved_write_frame(outfile, &packet);
838                 if (ret != 0) {
839                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
840                         break;
841                 }
842         }
843         avcodec_flush_buffers(get_codec_from_stream(video_stream));
844 }
845
846 /* **********************************************************************
847    * public interface
848    ********************************************************************** */
849
850 /* Get the output filename-- similar to the other output formats */
851 void filepath_ffmpeg(char* string, RenderData* rd) {
852         char autosplit[20];
853
854         const char ** exts = get_file_extensions(rd->ffcodecdata.type);
855         const char ** fe = exts;
856
857         if (!string || !exts) return;
858
859         strcpy(string, rd->pic);
860         BLI_path_abs(string, G.sce);
861
862         BLI_make_existing_file(string);
863
864         autosplit[0] = 0;
865
866         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
867                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
868         }
869
870         while (*fe) {
871                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
872                                    *fe) == 0) {
873                         break;
874                 }
875                 fe++;
876         }
877
878         if (!*fe) {
879                 strcat(string, autosplit);
880
881                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
882                 strcat(string, *exts);
883         } else {
884                 *(string + strlen(string) - strlen(*fe)) = 0;
885                 strcat(string, autosplit);
886                 strcat(string, *fe);
887         }
888 }
889
890 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
891 {
892         int success;
893
894         ffmpeg_autosplit_count = 0;
895
896         success = start_ffmpeg_impl(rd, rectx, recty, reports);
897
898         if(audio_stream)
899         {
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);
906         }
907
908         return success;
909 }
910
911 void end_ffmpeg(void);
912
913 static void write_audio_frames(double to_pts)
914 {
915         int finished = 0;
916
917         while (audio_stream && !finished) {
918                 if((audio_time >= to_pts) ||
919                    (write_audio_frame())) {
920                         finished = 1;
921                 }
922         }
923 }
924
925 int append_ffmpeg(RenderData *rd, int frame, int *pixels, int rectx, int recty, ReportList *reports) 
926 {
927         AVFrame* avframe;
928         int success = 1;
929
930         fprintf(stderr, "Writing frame %i, "
931                 "render width=%d, render height=%d\n", frame,
932                 rectx, recty);
933
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));
936
937         if(video_stream)
938         {
939                 avframe= generate_video_frame((unsigned char*) pixels, reports);
940                 success= (avframe && write_video_frame(rd, avframe, reports));
941
942                 if (ffmpeg_autosplit) {
943                         if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
944                                 end_ffmpeg();
945                                 ffmpeg_autosplit_count++;
946                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
947                         }
948                 }
949         }
950
951         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
952
953         return success;
954 }
955
956 void end_ffmpeg(void)
957 {
958         int i;
959         
960         fprintf(stderr, "Closing ffmpeg...\n");
961
962 /*      if (audio_stream) { SEE UPPER
963                 write_audio_frames();
964         }*/
965
966         if(audio_mixdown_device)
967         {
968                 AUD_closeReadDevice(audio_mixdown_device);
969                 audio_mixdown_device = 0;
970         }
971         
972         if (video_stream && get_codec_from_stream(video_stream)) {
973                 fprintf(stderr, "Flushing delayed frames...\n");
974                 flush_ffmpeg ();                
975         }
976         
977         if (outfile) {
978                 av_write_trailer(outfile);
979         }
980         
981         /* Close the video codec */
982
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);
986                 video_stream = 0;
987         }
988
989         
990         /* Close the output file */
991         if (outfile) {
992                 for (i = 0; i < outfile->nb_streams; i++) {
993                         if (&outfile->streams[i]) {
994                                 av_freep(&outfile->streams[i]);
995                         }
996                 }
997         }
998         /* free the temp buffer */
999         if (current_frame) {
1000                 delete_picture(current_frame);
1001                 current_frame = 0;
1002         }
1003         if (outfile && outfile->oformat) {
1004                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
1005                         url_fclose(OUTFILE_PB);
1006                 }
1007         }
1008         if (outfile) {
1009                 av_free(outfile);
1010                 outfile = 0;
1011         }
1012         if (video_buffer) {
1013                 MEM_freeN(video_buffer);
1014                 video_buffer = 0;
1015         }
1016         if (audio_output_buffer) {
1017                 MEM_freeN(audio_output_buffer);
1018                 audio_output_buffer = 0;
1019         }
1020         if (audio_input_buffer) {
1021                 MEM_freeN(audio_input_buffer);
1022                 audio_input_buffer = 0;
1023         }
1024
1025         if (img_convert_ctx) {
1026                 sws_freeContext(img_convert_ctx);
1027                 img_convert_ctx = 0;
1028         }
1029 }
1030
1031 /* properties */
1032
1033 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1034 {
1035         struct IDProperty *prop = (struct IDProperty *) prop_;
1036         IDProperty * group;
1037         
1038         if (!rd->ffcodecdata.properties) {
1039                 return;
1040         }
1041
1042         group = IDP_GetPropertyFromGroup(
1043                 rd->ffcodecdata.properties, (char*) type);
1044         if (group && prop) {
1045                 IDP_RemFromGroup(group, prop);
1046                 IDP_FreeProperty(prop);
1047                 MEM_freeN(prop);
1048         }
1049 }
1050
1051 IDProperty *ffmpeg_property_add(RenderData *rd, char * type, int opt_index, int parent_index)
1052 {
1053         AVCodecContext c;
1054         const AVOption * o;
1055         const AVOption * parent;
1056         IDProperty * group;
1057         IDProperty * prop;
1058         IDPropertyTemplate val;
1059         int idp_type;
1060         char name[256];
1061
1062         avcodec_get_context_defaults(&c);
1063
1064         o = c.av_class->option + opt_index;
1065         parent = c.av_class->option + parent_index;
1066
1067         if (!rd->ffcodecdata.properties) {
1068                 IDPropertyTemplate val;
1069
1070                 rd->ffcodecdata.properties 
1071                         = IDP_New(IDP_GROUP, val, "ffmpeg"); 
1072         }
1073
1074         group = IDP_GetPropertyFromGroup(
1075                 rd->ffcodecdata.properties, (char*) type);
1076         
1077         if (!group) {
1078                 IDPropertyTemplate val;
1079                 
1080                 group = IDP_New(IDP_GROUP, val, (char*) type); 
1081                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1082         }
1083
1084         if (parent_index) {
1085                 sprintf(name, "%s:%s", parent->name, o->name);
1086         } else {
1087                 strcpy(name, o->name);
1088         }
1089
1090         fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1091                 type, parent_index, opt_index, name);
1092
1093         prop = IDP_GetPropertyFromGroup(group, name);
1094         if (prop) {
1095                 return prop;
1096         }
1097
1098         switch (o->type) {
1099         case FF_OPT_TYPE_INT:
1100         case FF_OPT_TYPE_INT64:
1101                 val.i = o->default_val;
1102                 idp_type = IDP_INT;
1103                 break;
1104         case FF_OPT_TYPE_DOUBLE:
1105         case FF_OPT_TYPE_FLOAT:
1106                 val.f = o->default_val;
1107                 idp_type = IDP_FLOAT;
1108                 break;
1109         case FF_OPT_TYPE_STRING:
1110                 val.str = "                                                                               ";
1111                 idp_type = IDP_STRING;
1112                 break;
1113         case FF_OPT_TYPE_CONST:
1114                 val.i = 1;
1115                 idp_type = IDP_INT;
1116                 break;
1117         default:
1118                 return NULL;
1119         }
1120         prop = IDP_New(idp_type, val, name);
1121         IDP_AddToGroup(group, prop);
1122         return prop;
1123 }
1124
1125 /* not all versions of ffmpeg include that, so here we go ... */
1126
1127 static const AVOption *my_av_find_opt(void *v, const char *name, 
1128                                           const char *unit, int mask, int flags){
1129         AVClass *c= *(AVClass**)v; 
1130         const AVOption *o= c->option;
1131
1132         for(;o && o->name; o++){
1133                 if(!strcmp(o->name, name) && 
1134                    (!unit || (o->unit && !strcmp(o->unit, unit))) && 
1135                    (o->flags & mask) == flags )
1136                         return o;
1137         }
1138         return NULL;
1139 }
1140
1141 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1142 {
1143         AVCodecContext c;
1144         const AVOption * o = 0;
1145         const AVOption * p = 0;
1146         char name_[128];
1147         char * name;
1148         char * param;
1149         IDProperty * prop;
1150         
1151         avcodec_get_context_defaults(&c);
1152
1153         strncpy(name_, str, sizeof(name_));
1154
1155         name = name_;
1156         while (*name == ' ') name++;
1157
1158         param = strchr(name, ':');
1159
1160         if (!param) {
1161                 param = strchr(name, ' ');
1162         }
1163         if (param) {
1164                 *param++ = 0;
1165                 while (*param == ' ') param++;
1166         }
1167         
1168         o = my_av_find_opt(&c, name, NULL, 0, 0);       
1169         if (!o) {
1170                 return 0;
1171         }
1172         if (param && o->type == FF_OPT_TYPE_CONST) {
1173                 return 0;
1174         }
1175         if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1176                 p = my_av_find_opt(&c, param, o->unit, 0, 0);   
1177                 prop = ffmpeg_property_add(rd,
1178                         (char*) type, p - c.av_class->option, 
1179                         o - c.av_class->option);
1180         } else {
1181                 prop = ffmpeg_property_add(rd,
1182                         (char*) type, o - c.av_class->option, 0);
1183         }
1184                 
1185
1186         if (!prop) {
1187                 return 0;
1188         }
1189
1190         if (param && !p) {
1191                 switch (prop->type) {
1192                 case IDP_INT:
1193                         IDP_Int(prop) = atoi(param);
1194                         break;
1195                 case IDP_FLOAT:
1196                         IDP_Float(prop) = atof(param);
1197                         break;
1198                 case IDP_STRING:
1199                         strncpy(IDP_String(prop), param, prop->len);
1200                         break;
1201                 }
1202         }
1203         return 1;
1204 }
1205
1206 void ffmpeg_set_preset(RenderData *rd, int preset)
1207 {
1208         int isntsc = (rd->frs_sec != 25);
1209
1210         switch (preset) {
1211         case FFMPEG_PRESET_VCD:
1212                 rd->ffcodecdata.type = FFMPEG_MPEG1;
1213                 rd->ffcodecdata.video_bitrate = 1150;
1214                 rd->xsch = 352;
1215                 rd->ysch = isntsc ? 240 : 288;
1216                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1217                 rd->ffcodecdata.rc_max_rate = 1150;
1218                 rd->ffcodecdata.rc_min_rate = 1150;
1219                 rd->ffcodecdata.rc_buffer_size = 40*8;
1220                 rd->ffcodecdata.mux_packet_size = 2324;
1221                 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1222                 break;
1223
1224         case FFMPEG_PRESET_SVCD:
1225                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1226                 rd->ffcodecdata.video_bitrate = 2040;
1227                 rd->xsch = 480;
1228                 rd->ysch = isntsc ? 480 : 576;
1229                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1230                 rd->ffcodecdata.rc_max_rate = 2516;
1231                 rd->ffcodecdata.rc_min_rate = 0;
1232                 rd->ffcodecdata.rc_buffer_size = 224*8;
1233                 rd->ffcodecdata.mux_packet_size = 2324;
1234                 rd->ffcodecdata.mux_rate = 0;
1235                 break;
1236
1237         case FFMPEG_PRESET_DVD:
1238                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1239                 rd->ffcodecdata.video_bitrate = 6000;
1240                 rd->xsch = 720;
1241                 rd->ysch = isntsc ? 480 : 576;
1242                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1243                 rd->ffcodecdata.rc_max_rate = 9000;
1244                 rd->ffcodecdata.rc_min_rate = 0;
1245                 rd->ffcodecdata.rc_buffer_size = 224*8;
1246                 rd->ffcodecdata.mux_packet_size = 2048;
1247                 rd->ffcodecdata.mux_rate = 10080000;
1248                 break;
1249
1250         case FFMPEG_PRESET_DV:
1251                 rd->ffcodecdata.type = FFMPEG_DV;
1252                 rd->xsch = 720;
1253                 rd->ysch = isntsc ? 480 : 576;
1254                 break;
1255
1256         case FFMPEG_PRESET_H264:
1257                 rd->ffcodecdata.type = FFMPEG_AVI;
1258                 rd->ffcodecdata.codec = CODEC_ID_H264;
1259                 rd->ffcodecdata.video_bitrate = 6000;
1260                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1261                 rd->ffcodecdata.rc_max_rate = 9000;
1262                 rd->ffcodecdata.rc_min_rate = 0;
1263                 rd->ffcodecdata.rc_buffer_size = 224*8;
1264                 rd->ffcodecdata.mux_packet_size = 2048;
1265                 rd->ffcodecdata.mux_rate = 10080000;
1266
1267                 /*
1268                  * All options here are for x264, but must be set via ffmpeg.
1269                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1270                  * to get a list.
1271                  */
1272                 
1273                 /*
1274                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1275                  * crashes Blender for some reason. Either way - this is no big deal.
1276                  */
1277                 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1278                 
1279                 /* 
1280                  * The other options were taken from the libx264-default.preset
1281                  * included in the ffmpeg distribution.
1282                  */
1283                 ffmpeg_property_add_string(rd, "video", "flags:loop");
1284                 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1285                 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1286                 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1287                 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1288                 ffmpeg_property_add_string(rd, "video", "me:hex");
1289                 ffmpeg_property_add_string(rd, "video", "subq:6");
1290                 ffmpeg_property_add_string(rd, "video", "me_range:16");
1291                 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1292                 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1293                 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1294                 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1295                 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1296                 ffmpeg_property_add_string(rd, "video", "bf:3");
1297                 ffmpeg_property_add_string(rd, "video", "refs:2");
1298                 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1299                 ffmpeg_property_add_string(rd, "video", "directpred:3");
1300                 ffmpeg_property_add_string(rd, "video", "trellis:0");
1301                 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1302                 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1303                 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1304                 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1305                 
1306                 // This makes x264 output lossless. Will be a separate option later.
1307                 //ffmpeg_property_add_string(rd, "video", "cqp:0");
1308                 break;
1309
1310         case FFMPEG_PRESET_THEORA:
1311         case FFMPEG_PRESET_XVID:
1312                 if(preset == FFMPEG_PRESET_XVID) {
1313                         rd->ffcodecdata.type = FFMPEG_AVI;
1314                         rd->ffcodecdata.codec = CODEC_ID_XVID;
1315                 }
1316                 else if(preset == FFMPEG_PRESET_THEORA) {
1317                         rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1318                         rd->ffcodecdata.codec = CODEC_ID_THEORA;
1319                 }
1320
1321                 rd->ffcodecdata.video_bitrate = 6000;
1322                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1323                 rd->ffcodecdata.rc_max_rate = 9000;
1324                 rd->ffcodecdata.rc_min_rate = 0;
1325                 rd->ffcodecdata.rc_buffer_size = 224*8;
1326                 rd->ffcodecdata.mux_packet_size = 2048;
1327                 rd->ffcodecdata.mux_rate = 10080000;
1328                 break;
1329
1330         }
1331 }
1332
1333 void ffmpeg_verify_image_type(RenderData *rd)
1334 {
1335         int audio= 0;
1336
1337         if(rd->imtype == R_FFMPEG) {
1338                 if(rd->ffcodecdata.type <= 0 ||
1339                    rd->ffcodecdata.codec <= 0 ||
1340                    rd->ffcodecdata.audio_codec <= 0 ||
1341                    rd->ffcodecdata.video_bitrate <= 1) {
1342
1343                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1344                         /* Don't set preset, disturbs render resolution.
1345                          * ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD); */
1346                 }
1347
1348                 audio= 1;
1349         }
1350         else if(rd->imtype == R_H264) {
1351                 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1352                         ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1353                         audio= 1;
1354                 }
1355         }
1356         else if(rd->imtype == R_XVID) {
1357                 if(rd->ffcodecdata.codec != CODEC_ID_XVID) {
1358                         ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1359                         audio= 1;
1360                 }
1361         }
1362         else if(rd->imtype == R_THEORA) {
1363                 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1364                         ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1365                         audio= 1;
1366                 }
1367         }
1368
1369         if(audio && rd->ffcodecdata.audio_codec < 0) {
1370                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1371                 rd->ffcodecdata.audio_bitrate = 128;
1372         }
1373 }
1374
1375 #endif
1376