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