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