patch [#27887] LOSSLESS RENDERING: HuffYUV and FFV1 both fail to render losslessly
[blender-staging.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /** \file blender/blenkernel/intern/writeffmpeg.c
2  *  \ingroup bke
3  */
4 /*
5  * $Id$
6  *
7  * ffmpeg-write support
8  *
9  * Partial Copyright (c) 2006 Peter Schlaile
10  *
11  * This program is free software; you can redistribute it and/or modify
12  * it under the terms of the GNU General Public License as published by
13  * the Free Software Foundation; either version 2 of the License, or
14  * (at your option) any later version.
15  *
16  * This program is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
19  * GNU General Public License for more details.
20  *
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(
410                 rd->ffcodecdata.properties, (char*) prop_name);
411         if (!prop) {
412                 return;
413         }
414
415         iter = IDP_GetGroupIterator(prop);
416
417         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
418                 set_ffmpeg_property_option(c, curr);
419         }
420 }
421
422 /* prepare a video stream for the output file */
423
424 static AVStream* alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext* of,
425                                         int rectx, int recty) 
426 {
427         AVStream* st;
428         AVCodecContext* c;
429         AVCodec* codec;
430         st = av_new_stream(of, 0);
431         if (!st) return NULL;
432
433         /* Set up the codec context */
434         
435         c = st->codec;
436         c->codec_id = codec_id;
437         c->codec_type = AVMEDIA_TYPE_VIDEO;
438
439
440         /* Get some values from the current render settings */
441         
442         c->width = rectx;
443         c->height = recty;
444
445         /* FIXME: Really bad hack (tm) for NTSC support */
446         if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
447                 c->time_base.den = 2997;
448                 c->time_base.num = 100;
449         } else if ((double) ((int) rd->frs_sec_base) == 
450                    rd->frs_sec_base) {
451                 c->time_base.den = rd->frs_sec;
452                 c->time_base.num = (int) rd->frs_sec_base;
453         } else {
454                 c->time_base.den = rd->frs_sec * 100000;
455                 c->time_base.num = ((double) rd->frs_sec_base) * 100000;
456         }
457         
458         c->gop_size = ffmpeg_gop_size;
459         c->bit_rate = ffmpeg_video_bitrate*1000;
460         c->rc_max_rate = rd->ffcodecdata.rc_max_rate*1000;
461         c->rc_min_rate = rd->ffcodecdata.rc_min_rate*1000;
462         c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;
463         c->rc_initial_buffer_occupancy 
464                 = rd->ffcodecdata.rc_buffer_size*3/4;
465         c->rc_buffer_aggressivity = 1.0;
466         c->me_method = ME_EPZS;
467         
468         codec = avcodec_find_encoder(c->codec_id);
469         if (!codec) return NULL;
470         
471         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
472         
473         if (codec->pix_fmts) {
474                 c->pix_fmt = codec->pix_fmts[0];
475         } else {
476                 /* makes HuffYUV happy ... */
477                 c->pix_fmt = PIX_FMT_YUV422P;
478         }
479
480         if (ffmpeg_type == FFMPEG_XVID) {
481                 /* arghhhh ... */
482                 c->pix_fmt = PIX_FMT_YUV420P;
483                 c->codec_tag = (('D'<<24) + ('I'<<16) + ('V'<<8) + 'X');
484         }
485
486         if (codec_id == CODEC_ID_H264) {
487                 /* correct wrong default ffmpeg param which crash x264 */
488                 c->qmin=10;
489                 c->qmax=51;
490         }
491         
492         // Keep lossless encodes in the RGB domain.
493         if (codec_id == CODEC_ID_HUFFYUV || codec_id == CODEC_ID_FFV1) {
494                 /* HUFFYUV was PIX_FMT_YUV422P before */
495                 c->pix_fmt = PIX_FMT_RGB32;
496         }
497
498         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
499 //              || !strcmp(of->oformat->name, "mp4")
500 //          || !strcmp(of->oformat->name, "mov")
501 //          || !strcmp(of->oformat->name, "3gp")
502                 ) {
503                 fprintf(stderr, "Using global header\n");
504                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
505         }
506         
507         /* Determine whether we are encoding interlaced material or not */
508         if (rd->mode & R_FIELDS) {
509                 fprintf(stderr, "Encoding interlaced video\n");
510                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
511                 c->flags |= CODEC_FLAG_INTERLACED_ME;
512         }
513
514         /* xasp & yasp got float lately... */
515
516         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
517                 ((double) rd->xasp / (double) rd->yasp), 255);
518
519         set_ffmpeg_properties(rd, c, "video");
520         
521         if (avcodec_open(c, codec) < 0) {
522                 //
523                 //XXX error("Couldn't initialize codec");
524                 return NULL;
525         }
526
527         video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);
528         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize*sizeof(uint8_t),
529                                                  "FFMPEG video buffer");
530         
531         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
532
533         img_convert_ctx = sws_getContext(c->width, c->height,
534                                          PIX_FMT_BGR32,
535                                          c->width, c->height,
536                                          c->pix_fmt,
537                                          SWS_BICUBIC,
538                                          NULL, NULL, NULL);
539         return st;
540 }
541
542 /* Prepare an audio stream for the output file */
543
544 static AVStream* alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext* of) 
545 {
546         AVStream* st;
547         AVCodecContext* c;
548         AVCodec* codec;
549
550         st = av_new_stream(of, 1);
551         if (!st) return NULL;
552
553         c = st->codec;
554         c->codec_id = codec_id;
555         c->codec_type = AVMEDIA_TYPE_AUDIO;
556
557         c->sample_rate = rd->ffcodecdata.audio_mixrate;
558         c->bit_rate = ffmpeg_audio_bitrate*1000;
559         c->sample_fmt = SAMPLE_FMT_S16;
560         c->channels = rd->ffcodecdata.audio_channels;
561         codec = avcodec_find_encoder(c->codec_id);
562         if (!codec) {
563                 //XXX error("Couldn't find a valid audio codec");
564                 return NULL;
565         }
566
567         set_ffmpeg_properties(rd, c, "audio");
568
569         if (avcodec_open(c, codec) < 0) {
570                 //XXX error("Couldn't initialize audio codec");
571                 return NULL;
572         }
573
574         audio_outbuf_size = FF_MIN_BUFFER_SIZE;
575
576         if((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
577                 audio_input_samples = audio_outbuf_size * 8 / c->bits_per_coded_sample / c->channels;
578         else
579         {
580                 audio_input_samples = c->frame_size;
581                 if(c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
582                         audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
583         }
584
585         audio_output_buffer = (uint8_t*)av_malloc(
586                 audio_outbuf_size);
587
588         audio_input_buffer = (uint8_t*)av_malloc(
589                 audio_input_samples * c->channels * sizeof(int16_t));
590
591         audio_time = 0.0f;
592
593         return st;
594 }
595 /* essential functions -- start, append, end */
596
597 static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
598 {
599         /* Handle to the output file */
600         AVFormatContext* of;
601         AVOutputFormat* fmt;
602         char name[256];
603         const char ** exts;
604
605         ffmpeg_type = rd->ffcodecdata.type;
606         ffmpeg_codec = rd->ffcodecdata.codec;
607         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
608         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
609         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
610         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
611         ffmpeg_autosplit = rd->ffcodecdata.flags
612                 & FFMPEG_AUTOSPLIT_OUTPUT;
613         
614         do_init_ffmpeg();
615
616         /* Determine the correct filename */
617         filepath_ffmpeg(name, rd);
618         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
619                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
620                 "  video_bitrate=%d, audio_bitrate=%d,\n"
621                 "  gop_size=%d, autosplit=%d\n"
622                 "  render width=%d, render height=%d\n", 
623                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
624                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
625                 ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
626         
627         exts = get_file_extensions(ffmpeg_type);
628         if (!exts) {
629                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
630                 return 0;
631         }
632         fmt = av_guess_format(NULL, exts[0], NULL);
633         if (!fmt) {
634                 BKE_report(reports, RPT_ERROR, "No valid formats found.");
635                 return 0;
636         }
637
638         of = avformat_alloc_context();
639         if (!of) {
640                 BKE_report(reports, RPT_ERROR, "Error opening output file");
641                 return 0;
642         }
643         
644         of->oformat = fmt;
645         of->packet_size= rd->ffcodecdata.mux_packet_size;
646         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
647                 of->mux_rate = rd->ffcodecdata.mux_rate;
648         } else {
649                 of->mux_rate = 0;
650         }
651
652         of->preload = (int)(0.5*AV_TIME_BASE);
653         of->max_delay = (int)(0.7*AV_TIME_BASE);
654
655         fmt->audio_codec = ffmpeg_audio_codec;
656
657         BLI_snprintf(of->filename, sizeof(of->filename), "%s", name);
658         /* set the codec to the user's selection */
659         switch(ffmpeg_type) {
660         case FFMPEG_AVI:
661         case FFMPEG_MOV:
662         case FFMPEG_MKV:
663                 fmt->video_codec = ffmpeg_codec;
664                 break;
665         case FFMPEG_OGG:
666                 fmt->video_codec = CODEC_ID_THEORA;
667                 break;
668         case FFMPEG_DV:
669                 fmt->video_codec = CODEC_ID_DVVIDEO;
670                 break;
671         case FFMPEG_MPEG1:
672                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
673                 break;
674         case FFMPEG_MPEG2:
675                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
676                 break;
677         case FFMPEG_H264:
678                 fmt->video_codec = CODEC_ID_H264;
679                 break;
680         case FFMPEG_XVID:
681                 fmt->video_codec = CODEC_ID_MPEG4;
682                 break;
683         case FFMPEG_FLV:
684                 fmt->video_codec = CODEC_ID_FLV1;
685                 break;
686         case FFMPEG_MP3:
687                 fmt->audio_codec = CODEC_ID_MP3;
688         case FFMPEG_WAV:
689                 fmt->video_codec = CODEC_ID_NONE;
690                 break;
691         case FFMPEG_MPEG4:
692         default:
693                 fmt->video_codec = CODEC_ID_MPEG4;
694                 break;
695         }
696         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
697                 if (rectx != 720) {
698                         BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
699                         return 0;
700                 }
701                 if (rd->frs_sec != 25 && recty != 480) {
702                         BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
703                         return 0;
704                 }
705                 if (rd->frs_sec == 25 && recty != 576) {
706                         BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
707                         return 0;
708                 }
709         }
710         
711         if (ffmpeg_type == FFMPEG_DV) {
712                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
713                 if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
714                         BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
715                         return 0;
716                 }
717         }
718         
719         if (fmt->video_codec != CODEC_ID_NONE) {
720                 video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty);
721                 printf("alloc video stream %p\n", video_stream);
722                 if (!video_stream) {
723                         BKE_report(reports, RPT_ERROR, "Error initializing video stream.");
724                         return 0;
725                 }
726         }
727
728         if (ffmpeg_audio_codec != CODEC_ID_NONE) {
729                 audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of);
730                 if (!audio_stream) {
731                         BKE_report(reports, RPT_ERROR, "Error initializing audio stream.");
732                         return 0;
733                 }
734         }
735         if (av_set_parameters(of, NULL) < 0) {
736                 BKE_report(reports, RPT_ERROR, "Error setting output parameters.");
737                 return 0;
738         }
739         if (!(fmt->flags & AVFMT_NOFILE)) {
740                 if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
741                         BKE_report(reports, RPT_ERROR, "Could not open file for writing.");
742                         return 0;
743                 }
744         }
745
746         av_write_header(of);
747         outfile = of;
748         av_dump_format(of, 0, name, 1);
749
750         return 1;
751 }
752
753 /**
754  * Writes any delayed frames in the encoder. This function is called before 
755  * closing the encoder.
756  *
757  * <p>
758  * Since an encoder may use both past and future frames to predict 
759  * inter-frames (H.264 B-frames, for example), it can output the frames 
760  * in a different order from the one it was given.
761  * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
762  * them in the order 1, 4, 2, 3 - first the two frames used for predition, 
763  * and then the bidirectionally-predicted frames. What this means in practice 
764  * is that the encoder may not immediately produce one output frame for each 
765  * input frame. These delayed frames must be flushed before we close the 
766  * stream. We do this by calling avcodec_encode_video with NULL for the last 
767  * parameter.
768  * </p>
769  */
770 void flush_ffmpeg(void)
771 {
772         int outsize = 0;
773         int ret = 0;
774         
775         AVCodecContext* c = video_stream->codec;
776         /* get the delayed frames */
777         while (1) {
778                 AVPacket packet;
779                 av_init_packet(&packet);
780                 
781                 outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
782                 if (outsize < 0) {
783                         fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
784                         break;
785                 }
786                 if (outsize == 0) {
787                         break;
788                 }
789                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
790                         packet.pts = av_rescale_q(c->coded_frame->pts,
791                                                   c->time_base,
792                                                   video_stream->time_base);
793                         fprintf(stderr, "Video Frame PTS: %d\n", (int)packet.pts);
794                 } else {
795                         fprintf(stderr, "Video Frame PTS: not set\n");
796                 }
797                 if (c->coded_frame->key_frame) {
798                         packet.flags |= AV_PKT_FLAG_KEY;
799                 }
800                 packet.stream_index = video_stream->index;
801                 packet.data = video_buffer;
802                 packet.size = outsize;
803                 ret = av_interleaved_write_frame(outfile, &packet);
804                 if (ret != 0) {
805                         fprintf(stderr, "Error writing delayed frame %d\n", ret);
806                         break;
807                 }
808         }
809         avcodec_flush_buffers(video_stream->codec);
810 }
811
812 /* **********************************************************************
813    * public interface
814    ********************************************************************** */
815
816 /* Get the output filename-- similar to the other output formats */
817 void filepath_ffmpeg(char* string, RenderData* rd)
818 {
819         char autosplit[20];
820
821         const char ** exts = get_file_extensions(rd->ffcodecdata.type);
822         const char ** fe = exts;
823
824         if (!string || !exts) return;
825
826         strcpy(string, rd->pic);
827         BLI_path_abs(string, G.main->name);
828
829         BLI_make_existing_file(string);
830
831         autosplit[0] = 0;
832
833         if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
834                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
835         }
836
837         while (*fe) {
838                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
839                                    *fe) == 0) {
840                         break;
841                 }
842                 fe++;
843         }
844
845         if (!*fe) {
846                 strcat(string, autosplit);
847
848                 BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
849                 strcat(string, *exts);
850         } else {
851                 *(string + strlen(string) - strlen(*fe)) = 0;
852                 strcat(string, autosplit);
853                 strcat(string, *fe);
854         }
855 }
856
857 int start_ffmpeg(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
858 {
859         int success;
860
861         ffmpeg_autosplit_count = 0;
862
863         success = start_ffmpeg_impl(rd, rectx, recty, reports);
864 #ifdef WITH_AUDASPACE
865         if(audio_stream)
866         {
867                 AVCodecContext* c = audio_stream->codec;
868                 AUD_DeviceSpecs specs;
869                 specs.channels = c->channels;
870                 specs.format = AUD_FORMAT_S16;
871                 specs.rate = rd->ffcodecdata.audio_mixrate;
872                 audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
873 #ifdef FFMPEG_CODEC_TIME_BASE
874                 c->time_base.den = specs.rate;
875                 c->time_base.num = 1;
876 #endif
877         }
878 #endif
879         return success;
880 }
881
882 void end_ffmpeg(void);
883
884 #ifdef WITH_AUDASPACE
885 static void write_audio_frames(double to_pts)
886 {
887         int finished = 0;
888
889         while (audio_stream && !finished) {
890                 if((audio_time >= to_pts) ||
891                    (write_audio_frame())) {
892                         finished = 1;
893                 }
894         }
895 }
896 #endif
897
898 int append_ffmpeg(RenderData *rd, int frame, int *pixels, int rectx, int recty, ReportList *reports) 
899 {
900         AVFrame* avframe;
901         int success = 1;
902
903         fprintf(stderr, "Writing frame %i, "
904                 "render width=%d, render height=%d\n", frame,
905                 rectx, recty);
906
907 // why is this done before writing the video frame and again at end_ffmpeg?
908 //      write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));
909
910         if(video_stream)
911         {
912                 avframe= generate_video_frame((unsigned char*) pixels, reports);
913                 success= (avframe && write_video_frame(rd, avframe, reports));
914
915                 if (ffmpeg_autosplit) {
916                         if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
917                                 end_ffmpeg();
918                                 ffmpeg_autosplit_count++;
919                                 success &= start_ffmpeg_impl(rd, rectx, recty, reports);
920                         }
921                 }
922         }
923
924 #ifdef WITH_AUDASPACE
925         write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / rd->frs_sec_base));
926 #endif
927         return success;
928 }
929
930 void end_ffmpeg(void)
931 {
932         unsigned int i;
933         
934         fprintf(stderr, "Closing ffmpeg...\n");
935
936 /*      if (audio_stream) { SEE UPPER
937                 write_audio_frames();
938         }*/
939
940 #ifdef WITH_AUDASPACE
941         if(audio_mixdown_device)
942         {
943                 AUD_closeReadDevice(audio_mixdown_device);
944                 audio_mixdown_device = 0;
945         }
946 #endif
947
948         if (video_stream && video_stream->codec) {
949                 fprintf(stderr, "Flushing delayed frames...\n");
950                 flush_ffmpeg ();                
951         }
952         
953         if (outfile) {
954                 av_write_trailer(outfile);
955         }
956         
957         /* Close the video codec */
958
959         if (video_stream && video_stream->codec) {
960                 avcodec_close(video_stream->codec);
961                 printf("zero video stream %p\n", video_stream);
962                 video_stream = 0;
963         }
964
965         
966         /* Close the output file */
967         if (outfile) {
968                 for (i = 0; i < outfile->nb_streams; i++) {
969                         if (&outfile->streams[i]) {
970                                 av_freep(&outfile->streams[i]);
971                         }
972                 }
973         }
974         /* free the temp buffer */
975         if (current_frame) {
976                 delete_picture(current_frame);
977                 current_frame = 0;
978         }
979         if (outfile && outfile->oformat) {
980                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
981                         avio_close(outfile->pb);
982                 }
983         }
984         if (outfile) {
985                 av_free(outfile);
986                 outfile = 0;
987         }
988         if (video_buffer) {
989                 MEM_freeN(video_buffer);
990                 video_buffer = 0;
991         }
992         if (audio_output_buffer) {
993                 av_free(audio_output_buffer);
994                 audio_output_buffer = 0;
995         }
996         if (audio_input_buffer) {
997                 av_free(audio_input_buffer);
998                 audio_input_buffer = 0;
999         }
1000
1001         if (img_convert_ctx) {
1002                 sws_freeContext(img_convert_ctx);
1003                 img_convert_ctx = 0;
1004         }
1005 }
1006
1007 /* properties */
1008
1009 void ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
1010 {
1011         struct IDProperty *prop = (struct IDProperty *) prop_;
1012         IDProperty * group;
1013         
1014         if (!rd->ffcodecdata.properties) {
1015                 return;
1016         }
1017
1018         group = IDP_GetPropertyFromGroup(
1019                 rd->ffcodecdata.properties, (char*) type);
1020         if (group && prop) {
1021                 IDP_RemFromGroup(group, prop);
1022                 IDP_FreeProperty(prop);
1023                 MEM_freeN(prop);
1024         }
1025 }
1026
1027 IDProperty *ffmpeg_property_add(RenderData *rd, char * type, int opt_index, int parent_index)
1028 {
1029         AVCodecContext c;
1030         const AVOption * o;
1031         const AVOption * parent;
1032         IDProperty * group;
1033         IDProperty * prop;
1034         IDPropertyTemplate val;
1035         int idp_type;
1036         char name[256];
1037         
1038         val.i = 0;
1039
1040         avcodec_get_context_defaults(&c);
1041
1042         o = c.av_class->option + opt_index;
1043         parent = c.av_class->option + parent_index;
1044
1045         if (!rd->ffcodecdata.properties) {
1046                 rd->ffcodecdata.properties 
1047                         = IDP_New(IDP_GROUP, val, "ffmpeg"); 
1048         }
1049
1050         group = IDP_GetPropertyFromGroup(
1051                 rd->ffcodecdata.properties, (char*) type);
1052         
1053         if (!group) {
1054                 group = IDP_New(IDP_GROUP, val, (char*) type); 
1055                 IDP_AddToGroup(rd->ffcodecdata.properties, group);
1056         }
1057
1058         if (parent_index) {
1059                 sprintf(name, "%s:%s", parent->name, o->name);
1060         } else {
1061                 strcpy(name, o->name);
1062         }
1063
1064         fprintf(stderr, "ffmpeg_property_add: %s %d %d %s\n",
1065                 type, parent_index, opt_index, name);
1066
1067         prop = IDP_GetPropertyFromGroup(group, name);
1068         if (prop) {
1069                 return prop;
1070         }
1071
1072         switch (o->type) {
1073         case FF_OPT_TYPE_INT:
1074         case FF_OPT_TYPE_INT64:
1075                 val.i = FFMPEG_DEF_OPT_VAL_INT(o);
1076                 idp_type = IDP_INT;
1077                 break;
1078         case FF_OPT_TYPE_DOUBLE:
1079         case FF_OPT_TYPE_FLOAT:
1080                 val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
1081                 idp_type = IDP_FLOAT;
1082                 break;
1083         case FF_OPT_TYPE_STRING:
1084                 val.str = "                                                                               ";
1085                 idp_type = IDP_STRING;
1086                 break;
1087         case FF_OPT_TYPE_CONST:
1088                 val.i = 1;
1089                 idp_type = IDP_INT;
1090                 break;
1091         default:
1092                 return NULL;
1093         }
1094         prop = IDP_New(idp_type, val, name);
1095         IDP_AddToGroup(group, prop);
1096         return prop;
1097 }
1098
1099 /* not all versions of ffmpeg include that, so here we go ... */
1100
1101 static const AVOption *my_av_find_opt(void *v, const char *name, 
1102                                           const char *unit, int mask, int flags){
1103         AVClass *c= *(AVClass**)v; 
1104         const AVOption *o= c->option;
1105
1106         for(;o && o->name; o++){
1107                 if(!strcmp(o->name, name) && 
1108                    (!unit || (o->unit && !strcmp(o->unit, unit))) && 
1109                    (o->flags & mask) == flags )
1110                         return o;
1111         }
1112         return NULL;
1113 }
1114
1115 int ffmpeg_property_add_string(RenderData *rd, const char * type, const char * str)
1116 {
1117         AVCodecContext c;
1118         const AVOption * o = 0;
1119         const AVOption * p = 0;
1120         char name_[128];
1121         char * name;
1122         char * param;
1123         IDProperty * prop;
1124         
1125         avcodec_get_context_defaults(&c);
1126
1127         strncpy(name_, str, sizeof(name_));
1128
1129         name = name_;
1130         while (*name == ' ') name++;
1131
1132         param = strchr(name, ':');
1133
1134         if (!param) {
1135                 param = strchr(name, ' ');
1136         }
1137         if (param) {
1138                 *param++ = 0;
1139                 while (*param == ' ') param++;
1140         }
1141         
1142         o = my_av_find_opt(&c, name, NULL, 0, 0);       
1143         if (!o) {
1144                 return 0;
1145         }
1146         if (param && o->type == FF_OPT_TYPE_CONST) {
1147                 return 0;
1148         }
1149         if (param && o->type != FF_OPT_TYPE_CONST && o->unit) {
1150                 p = my_av_find_opt(&c, param, o->unit, 0, 0);   
1151                 prop = ffmpeg_property_add(rd,
1152                         (char*) type, p - c.av_class->option, 
1153                         o - c.av_class->option);
1154         } else {
1155                 prop = ffmpeg_property_add(rd,
1156                         (char*) type, o - c.av_class->option, 0);
1157         }
1158                 
1159
1160         if (!prop) {
1161                 return 0;
1162         }
1163
1164         if (param && !p) {
1165                 switch (prop->type) {
1166                 case IDP_INT:
1167                         IDP_Int(prop) = atoi(param);
1168                         break;
1169                 case IDP_FLOAT:
1170                         IDP_Float(prop) = atof(param);
1171                         break;
1172                 case IDP_STRING:
1173                         strncpy(IDP_String(prop), param, prop->len);
1174                         break;
1175                 }
1176         }
1177         return 1;
1178 }
1179
1180 void ffmpeg_set_preset(RenderData *rd, int preset)
1181 {
1182         int isntsc = (rd->frs_sec != 25);
1183
1184         switch (preset) {
1185         case FFMPEG_PRESET_VCD:
1186                 rd->ffcodecdata.type = FFMPEG_MPEG1;
1187                 rd->ffcodecdata.video_bitrate = 1150;
1188                 rd->xsch = 352;
1189                 rd->ysch = isntsc ? 240 : 288;
1190                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1191                 rd->ffcodecdata.rc_max_rate = 1150;
1192                 rd->ffcodecdata.rc_min_rate = 1150;
1193                 rd->ffcodecdata.rc_buffer_size = 40*8;
1194                 rd->ffcodecdata.mux_packet_size = 2324;
1195                 rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
1196                 break;
1197
1198         case FFMPEG_PRESET_SVCD:
1199                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1200                 rd->ffcodecdata.video_bitrate = 2040;
1201                 rd->xsch = 480;
1202                 rd->ysch = isntsc ? 480 : 576;
1203                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1204                 rd->ffcodecdata.rc_max_rate = 2516;
1205                 rd->ffcodecdata.rc_min_rate = 0;
1206                 rd->ffcodecdata.rc_buffer_size = 224*8;
1207                 rd->ffcodecdata.mux_packet_size = 2324;
1208                 rd->ffcodecdata.mux_rate = 0;
1209                 break;
1210
1211         case FFMPEG_PRESET_DVD:
1212                 rd->ffcodecdata.type = FFMPEG_MPEG2;
1213                 rd->ffcodecdata.video_bitrate = 6000;
1214                 rd->xsch = 720;
1215                 rd->ysch = isntsc ? 480 : 576;
1216                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1217                 rd->ffcodecdata.rc_max_rate = 9000;
1218                 rd->ffcodecdata.rc_min_rate = 0;
1219                 rd->ffcodecdata.rc_buffer_size = 224*8;
1220                 rd->ffcodecdata.mux_packet_size = 2048;
1221                 rd->ffcodecdata.mux_rate = 10080000;
1222                 break;
1223
1224         case FFMPEG_PRESET_DV:
1225                 rd->ffcodecdata.type = FFMPEG_DV;
1226                 rd->xsch = 720;
1227                 rd->ysch = isntsc ? 480 : 576;
1228                 break;
1229
1230         case FFMPEG_PRESET_H264:
1231                 rd->ffcodecdata.type = FFMPEG_AVI;
1232                 rd->ffcodecdata.codec = CODEC_ID_H264;
1233                 rd->ffcodecdata.video_bitrate = 6000;
1234                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1235                 rd->ffcodecdata.rc_max_rate = 9000;
1236                 rd->ffcodecdata.rc_min_rate = 0;
1237                 rd->ffcodecdata.rc_buffer_size = 224*8;
1238                 rd->ffcodecdata.mux_packet_size = 2048;
1239                 rd->ffcodecdata.mux_rate = 10080000;
1240
1241                 /*
1242                  * All options here are for x264, but must be set via ffmpeg.
1243                  * The names are therefore different - Search for "x264 to FFmpeg option mapping"
1244                  * to get a list.
1245                  */
1246                 
1247                 /*
1248                  * Use CABAC coder. Using "coder:1", which should be equivalent,
1249                  * crashes Blender for some reason. Either way - this is no big deal.
1250                  */
1251                 ffmpeg_property_add_string(rd, "video", "coder:vlc");
1252                 
1253                 /* 
1254                  * The other options were taken from the libx264-default.preset
1255                  * included in the ffmpeg distribution.
1256                  */
1257                 ffmpeg_property_add_string(rd, "video", "flags:loop");
1258                 ffmpeg_property_add_string(rd, "video", "cmp:chroma");
1259                 ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
1260                 ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
1261                 ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
1262                 ffmpeg_property_add_string(rd, "video", "me:hex");
1263                 ffmpeg_property_add_string(rd, "video", "subq:6");
1264                 ffmpeg_property_add_string(rd, "video", "me_range:16");
1265                 ffmpeg_property_add_string(rd, "video", "qdiff:4");
1266                 ffmpeg_property_add_string(rd, "video", "keyint_min:25");
1267                 ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
1268                 ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
1269                 ffmpeg_property_add_string(rd, "video", "b_strategy:1");
1270                 ffmpeg_property_add_string(rd, "video", "bf:3");
1271                 ffmpeg_property_add_string(rd, "video", "refs:2");
1272                 ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
1273                 ffmpeg_property_add_string(rd, "video", "directpred:3");
1274                 ffmpeg_property_add_string(rd, "video", "trellis:0");
1275                 ffmpeg_property_add_string(rd, "video", "flags2:wpred");
1276                 ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
1277                 ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
1278                 ffmpeg_property_add_string(rd, "video", "wpredp:2");
1279                 
1280                 // This makes x264 output lossless. Will be a separate option later.
1281                 //ffmpeg_property_add_string(rd, "video", "cqp:0");
1282                 break;
1283
1284         case FFMPEG_PRESET_THEORA:
1285         case FFMPEG_PRESET_XVID:
1286                 if(preset == FFMPEG_PRESET_XVID) {
1287                         rd->ffcodecdata.type = FFMPEG_AVI;
1288                         rd->ffcodecdata.codec = CODEC_ID_MPEG4;
1289                 }
1290                 else if(preset == FFMPEG_PRESET_THEORA) {
1291                         rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
1292                         rd->ffcodecdata.codec = CODEC_ID_THEORA;
1293                 }
1294
1295                 rd->ffcodecdata.video_bitrate = 6000;
1296                 rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
1297                 rd->ffcodecdata.rc_max_rate = 9000;
1298                 rd->ffcodecdata.rc_min_rate = 0;
1299                 rd->ffcodecdata.rc_buffer_size = 224*8;
1300                 rd->ffcodecdata.mux_packet_size = 2048;
1301                 rd->ffcodecdata.mux_rate = 10080000;
1302                 break;
1303
1304         }
1305 }
1306
1307 void ffmpeg_verify_image_type(RenderData *rd)
1308 {
1309         int audio= 0;
1310
1311         if(rd->imtype == R_FFMPEG) {
1312                 if(rd->ffcodecdata.type <= 0 ||
1313                    rd->ffcodecdata.codec <= 0 ||
1314                    rd->ffcodecdata.audio_codec <= 0 ||
1315                    rd->ffcodecdata.video_bitrate <= 1) {
1316
1317                         rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;
1318                         /* Don't set preset, disturbs render resolution.
1319                          * ffmpeg_set_preset(rd, FFMPEG_PRESET_DVD); */
1320                 }
1321                 if(rd->ffcodecdata.type == FFMPEG_OGG) {
1322                         rd->ffcodecdata.type = FFMPEG_MPEG2;
1323                 }
1324
1325                 audio= 1;
1326         }
1327         else if(rd->imtype == R_H264) {
1328                 if(rd->ffcodecdata.codec != CODEC_ID_H264) {
1329                         ffmpeg_set_preset(rd, FFMPEG_PRESET_H264);
1330                         audio= 1;
1331                 }
1332         }
1333         else if(rd->imtype == R_XVID) {
1334                 if(rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
1335                         ffmpeg_set_preset(rd, FFMPEG_PRESET_XVID);
1336                         audio= 1;
1337                 }
1338         }
1339         else if(rd->imtype == R_THEORA) {
1340                 if(rd->ffcodecdata.codec != CODEC_ID_THEORA) {
1341                         ffmpeg_set_preset(rd, FFMPEG_PRESET_THEORA);
1342                         audio= 1;
1343                 }
1344         }
1345
1346         if(audio && rd->ffcodecdata.audio_codec < 0) {
1347                 rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
1348                 rd->ffcodecdata.audio_bitrate = 128;
1349         }
1350 }
1351
1352 #endif
1353