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