Move variable declaration, wouldn't compiler with MSVC (reports by jms).
[blender.git] / source / blender / blenkernel / intern / writeffmpeg.c
1 /*
2  * ffmpeg-write support
3  *
4  * Partial Copyright (c) 2006 Peter Schlaile
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  */
17
18
19 #ifdef WITH_FFMPEG
20 #include <string.h>
21 #include <stdio.h>
22
23 #if defined(_WIN32) && defined(_DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
24 /* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
25 #if _MSC_VER < 1400
26 #include <stdint.h>
27 #endif
28 #endif
29
30 #include <stdlib.h>
31
32 #include <ffmpeg/avformat.h>
33 #include <ffmpeg/avcodec.h>
34 #include <ffmpeg/rational.h>
35 #include <ffmpeg/swscale.h>
36 #include <ffmpeg/opt.h>
37
38 #if LIBAVFORMAT_VERSION_INT < (49 << 16)
39 #define FFMPEG_OLD_FRAME_RATE 1
40 #else
41 #define FFMPEG_CODEC_IS_POINTER 1
42 #define FFMPEG_CODEC_TIME_BASE  1
43 #endif
44
45 #if LIBAVFORMAT_VERSION_INT >= (52 << 16)
46 #define OUTFILE_PB (outfile->pb)
47 #else
48 #define OUTFILE_PB (&outfile->pb)
49 #endif
50
51 #if defined(WIN32) && (!(defined snprintf))
52 #define snprintf _snprintf
53 #endif
54
55 #include "BKE_writeffmpeg.h"
56
57 #include "MEM_guardedalloc.h"
58 #include "BLI_blenlib.h"
59
60 #include "BKE_bad_level_calls.h"
61 #include "BKE_global.h"
62 #include "BKE_idprop.h"
63
64 #include "IMB_imbuf_types.h"
65 #include "IMB_imbuf.h"
66
67 #include "BSE_seqaudio.h"
68
69 #include "DNA_scene_types.h"
70 #include "blendef.h"
71
72 #ifdef HAVE_CONFIG_H
73 #include <config.h>
74 #endif
75
76 extern void do_init_ffmpeg();
77 void makeffmpegstring(char* string);
78
79 static int ffmpeg_type = 0;
80 static int ffmpeg_codec = CODEC_ID_MPEG4;
81 static int ffmpeg_audio_codec = CODEC_ID_MP2;
82 static int ffmpeg_video_bitrate = 1150;
83 static int ffmpeg_audio_bitrate = 128;
84 static int ffmpeg_gop_size = 12;
85 static int ffmpeg_multiplex_audio = 1;
86 static int ffmpeg_autosplit = 0;
87 static int ffmpeg_autosplit_count = 0;
88
89 static AVFormatContext* outfile = 0;
90 static AVStream* video_stream = 0;
91 static AVStream* audio_stream = 0;
92 static AVFrame* current_frame = 0;
93 static struct SwsContext *img_convert_ctx = 0;
94
95 static uint8_t* video_buffer = 0;
96 static int video_buffersize = 0;
97
98 static uint8_t* audio_input_buffer = 0;
99 static int audio_input_frame_size = 0;
100 static uint8_t* audio_output_buffer = 0;
101 static int audio_outbuf_size = 0;
102
103 static RenderData *ffmpeg_renderdata = 0;
104
105 #define FFMPEG_AUTOSPLIT_SIZE 2000000000
106
107 /* Delete a picture buffer */
108
109 static void delete_picture(AVFrame* f)
110 {
111         if (f) {
112                 if (f->data[0]) MEM_freeN(f->data[0]);
113                 av_free(f);
114         }
115 }
116
117 #ifdef FFMPEG_CODEC_IS_POINTER
118 static AVCodecContext* get_codec_from_stream(AVStream* stream)
119 {
120         return stream->codec;
121 }
122 #else
123 static AVCodecContext* get_codec_from_stream(AVStream* stream)
124 {
125         return &stream->codec;
126 }
127 #endif
128
129 static int write_audio_frame(void) 
130 {
131         AVCodecContext* c = NULL;
132         AVPacket pkt;
133
134         c = get_codec_from_stream(audio_stream);
135
136         audiostream_fill(audio_input_buffer, 
137                          audio_input_frame_size 
138                          * sizeof(short) * c->channels);
139
140         av_init_packet(&pkt);
141
142         pkt.size = avcodec_encode_audio(c, audio_output_buffer,
143                                         audio_outbuf_size, 
144                                         (short*) audio_input_buffer);
145         pkt.data = audio_output_buffer;
146 #ifdef FFMPEG_CODEC_TIME_BASE
147         pkt.pts = av_rescale_q(c->coded_frame->pts, 
148                                c->time_base, audio_stream->time_base);
149 #else
150         pkt.pts = c->coded_frame->pts;
151 #endif
152         fprintf(stderr, "Audio Frame PTS: %lld\n", pkt.pts);
153
154         pkt.stream_index = audio_stream->index;
155         pkt.flags |= PKT_FLAG_KEY;
156         if (av_interleaved_write_frame(outfile, &pkt) != 0) {
157                 error("Error writing audio packet");
158                 return -1;
159         }
160         return 0;
161 }
162
163 /* Allocate a temporary frame */
164 static AVFrame* alloc_picture(int pix_fmt, int width, int height) 
165 {
166         AVFrame* f;
167         uint8_t* buf;
168         int size;
169         
170         /* allocate space for the struct */
171         f = avcodec_alloc_frame();
172         if (!f) return NULL;
173         size = avpicture_get_size(pix_fmt, width, height);
174         /* allocate the actual picture buffer */
175         buf = MEM_mallocN(size, "AVFrame buffer");
176         if (!buf) {
177                 free(f);
178                 return NULL;
179         }
180         avpicture_fill((AVPicture*)f, buf, pix_fmt, width, height);
181         return f;
182 }
183
184 /* Get the correct file extensions for the requested format,
185    first is always desired guess_format parameter */
186 static const char** get_file_extensions(int format) 
187 {
188         switch(format) {
189         case FFMPEG_DV: {
190                 static const char * rv[] = { ".dv", NULL };
191                 return rv;
192         }
193         case FFMPEG_MPEG1: {
194                 static const char * rv[] = { ".mpg", ".mpeg", NULL };
195                 return rv;
196         }
197         case FFMPEG_MPEG2: {
198                 static const char * rv[] = { ".dvd", ".vob", ".mpg", ".mpeg",
199                                              NULL };
200                 return rv;
201         }
202         case FFMPEG_MPEG4: {
203                 static const char * rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
204                 return rv;
205         }
206         case FFMPEG_AVI: {
207                 static const char * rv[] = { ".avi", NULL };
208                 return rv;
209         }
210         case FFMPEG_MOV: {
211                 static const char * rv[] = { ".mov", NULL };
212                 return rv;
213         }
214         case FFMPEG_H264: {
215                 /* FIXME: avi for now... */
216                 static const char * rv[] = { ".avi", NULL };
217                 return rv;
218         }
219
220         case FFMPEG_XVID: {
221                 /* FIXME: avi for now... */
222                 static const char * rv[] = { ".avi", NULL };
223                 return rv;
224         }
225         case FFMPEG_FLV: {
226                 static const char * rv[] = { ".flv", NULL };
227                 return rv;
228         }
229         default:
230                 return NULL;
231         }
232 }
233
234 /* Write a frame to the output file */
235 static void write_video_frame(AVFrame* frame) 
236 {
237         int outsize = 0;
238         int ret;
239         AVCodecContext* c = get_codec_from_stream(video_stream);
240 #ifdef FFMPEG_CODEC_TIME_BASE
241         frame->pts = G.scene->r.cfra - G.scene->r.sfra;
242 #endif
243
244         outsize = avcodec_encode_video(c, video_buffer, video_buffersize, 
245                                        frame);
246         if (outsize != 0) {
247                 AVPacket packet;
248                 av_init_packet(&packet);
249
250 #ifdef FFMPEG_CODEC_TIME_BASE
251                 packet.pts = av_rescale_q(c->coded_frame->pts,
252                                           c->time_base,
253                                           video_stream->time_base);
254 #else
255                 packet.pts = c->coded_frame->pts;
256 #endif
257                 fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
258                 if (c->coded_frame->key_frame)
259                         packet.flags |= PKT_FLAG_KEY;
260                 packet.stream_index = video_stream->index;
261                 packet.data = video_buffer;
262                 packet.size = outsize;
263                 ret = av_interleaved_write_frame(outfile, &packet);
264         } else ret = 0;
265         if (ret != 0) {
266                 G.afbreek = 1;
267                 error("Error writing frame");
268         }
269 }
270
271 /* read and encode a frame of audio from the buffer */
272 static AVFrame* generate_video_frame(uint8_t* pixels) 
273 {
274         uint8_t* rendered_frame;
275
276         AVCodecContext* c = get_codec_from_stream(video_stream);
277         int width = c->width;
278         int height = c->height;
279         AVFrame* rgb_frame;
280
281         if (c->pix_fmt != PIX_FMT_RGBA32) {
282                 rgb_frame = alloc_picture(PIX_FMT_RGBA32, width, height);
283                 if (!rgb_frame) {
284                         G.afbreek=1;
285                         error("Couldn't allocate temporary frame");
286                         return NULL;
287                 }
288         } else {
289                 rgb_frame = current_frame;
290         }
291
292         rendered_frame = pixels;
293
294         /* Do RGBA-conversion and flipping in one step depending
295            on CPU-Endianess */
296
297         if (G.order == L_ENDIAN) {
298                 int y;
299                 for (y = 0; y < height; y++) {
300                         uint8_t* target = rgb_frame->data[0]
301                                 + width * 4 * (height - y - 1);
302                         uint8_t* src = rendered_frame + width * 4 * y;
303                         uint8_t* end = src + width * 4;
304                         while (src != end) {
305                                 target[3] = src[3];
306                                 target[2] = src[0];
307                                 target[1] = src[1];
308                                 target[0] = src[2];
309
310                                 target += 4;
311                                 src += 4;
312                         }
313                 }
314         } else {
315                 int y;
316                 for (y = 0; y < height; y++) {
317                         uint8_t* target = rgb_frame->data[0]
318                                 + width * 4 * (height - y - 1);
319                         uint8_t* src = rendered_frame + width * 4 * y;
320                         uint8_t* end = src + width * 4;
321                         while (src != end) {
322                                 target[3] = src[2];
323                                 target[2] = src[1];
324                                 target[1] = src[0];
325                                 target[0] = src[3];
326
327                                 target += 4;
328                                 src += 4;
329                         }
330                 }
331         }
332
333         if (c->pix_fmt != PIX_FMT_RGBA32) {
334                 sws_scale(img_convert_ctx, rgb_frame->data,
335                           rgb_frame->linesize, 0, c->height, 
336                           current_frame->data, current_frame->linesize);
337                 delete_picture(rgb_frame);
338         }
339         return current_frame;
340 }
341
342 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
343 {
344         char name[128];
345         char * param;
346         const AVOption * rv = NULL;
347
348         fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
349
350         strncpy(name, prop->name, 128);
351
352         param = strchr(name, ':');
353
354         if (param) {
355                 *param++ = 0;
356         }
357
358         switch(prop->type) {
359         case IDP_STRING:
360                 fprintf(stderr, "%s.\n", IDP_String(prop));
361                 rv = av_set_string(c, prop->name, IDP_String(prop));
362                 break;
363         case IDP_FLOAT:
364                 fprintf(stderr, "%g.\n", IDP_Float(prop));
365                 rv = av_set_double(c, prop->name, IDP_Float(prop));
366                 break;
367         case IDP_INT:
368                 fprintf(stderr, "%d.\n", IDP_Int(prop));
369                 
370                 if (param) {
371                         if (IDP_Int(prop)) {
372                                 rv = av_set_string(c, name, param);
373                         } else {
374                                 return;
375                         }
376                 } else {
377                         rv = av_set_int(c, prop->name, IDP_Int(prop));
378                 }
379                 break;
380         }
381
382         if (!rv) {
383                 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
384                         prop->name);
385         }
386 }
387
388 static void set_ffmpeg_properties(AVCodecContext* c, const char * prop_name)
389 {
390         IDProperty * prop;
391         void * iter;
392         IDProperty * curr;
393
394         if (!G.scene->r.ffcodecdata.properties) {
395                 return;
396         }
397         
398         prop = IDP_GetPropertyFromGroup(
399                 G.scene->r.ffcodecdata.properties, (char*) prop_name);
400         if (!prop) {
401                 return;
402         }
403
404         iter = IDP_GetGroupIterator(prop);
405
406         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
407                 set_ffmpeg_property_option(c, curr);
408         }
409 }
410
411 /* prepare a video stream for the output file */
412
413 static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
414                                     int rectx, int recty) 
415 {
416         AVStream* st;
417         AVCodecContext* c;
418         AVCodec* codec;
419         st = av_new_stream(of, 0);
420         if (!st) return NULL;
421
422         /* Set up the codec context */
423         
424         c = get_codec_from_stream(st);
425         c->codec_id = codec_id;
426         c->codec_type = CODEC_TYPE_VIDEO;
427
428
429         /* Get some values from the current render settings */
430         
431         c->width = rectx;
432         c->height = recty;
433
434 #ifdef FFMPEG_CODEC_TIME_BASE
435         /* FIXME: Really bad hack (tm) for NTSC support */
436         if (ffmpeg_type == FFMPEG_DV && G.scene->r.frs_sec != 25) {
437                 c->time_base.den = 2997;
438                 c->time_base.num = 100;
439         } else if ((double) ((int) G.scene->r.frs_sec_base) == 
440                    G.scene->r.frs_sec_base) {
441                 c->time_base.den = G.scene->r.frs_sec;
442                 c->time_base.num = (int) G.scene->r.frs_sec_base;
443         } else {
444                 c->time_base.den = G.scene->r.frs_sec * 100000;
445                 c->time_base.num = ((double) G.scene->r.frs_sec_base) * 100000;
446         }
447 #else
448         /* FIXME: Really bad hack (tm) for NTSC support */
449         if (ffmpeg_type == FFMPEG_DV && G.scene->r.frs_sec != 25) {
450                 c->frame_rate = 2997;
451                 c->frame_rate_base = 100;
452         } else if ((double) ((int) G.scene->r.frs_sec_base) == 
453                    G.scene->r.frs_sec_base) {
454                 c->frame_rate = G.scene->r.frs_sec;
455                 c->frame_rate_base = G.scene->r.frs_sec_base;
456         } else {
457                 c->frame_rate = G.scene->r.frs_sec * 100000;
458                 c->frame_rate_base = ((double) G.scene->r.frs_sec_base)*100000;
459         }
460 #endif
461         
462         c->gop_size = ffmpeg_gop_size;
463         c->bit_rate = ffmpeg_video_bitrate*1000;
464         c->rc_max_rate = G.scene->r.ffcodecdata.rc_max_rate*1000;
465         c->rc_min_rate = G.scene->r.ffcodecdata.rc_min_rate*1000;
466         c->rc_buffer_size = G.scene->r.ffcodecdata.rc_buffer_size * 1024;
467         c->rc_initial_buffer_occupancy 
468                 = G.scene->r.ffcodecdata.rc_buffer_size*3/4;
469         c->rc_buffer_aggressivity = 1.0;
470         c->me_method = ME_EPZS;
471         
472         codec = avcodec_find_encoder(c->codec_id);
473         if (!codec) return NULL;
474         
475         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
476         
477         if (codec->pix_fmts) {
478                 c->pix_fmt = codec->pix_fmts[0];
479         } else {
480                 /* makes HuffYUV happy ... */
481                 c->pix_fmt = PIX_FMT_YUV422P;
482         }
483
484         if (codec_id == CODEC_ID_XVID) {
485                 /* arghhhh ... */
486                 c->pix_fmt = PIX_FMT_YUV420P;
487         }
488         
489         if (!strcmp(of->oformat->name, "mp4") || 
490             !strcmp(of->oformat->name, "mov") ||
491             !strcmp(of->oformat->name, "3gp")) {
492                 fprintf(stderr, "Using global header\n");
493                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
494         }
495         
496         /* Determine whether we are encoding interlaced material or not */
497         if (G.scene->r.mode & R_FIELDS) {
498                 fprintf(stderr, "Encoding interlaced video\n");
499                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
500                 c->flags |= CODEC_FLAG_INTERLACED_ME;
501         }
502
503         /* xasp & yasp got float lately... */
504
505         c->sample_aspect_ratio = av_d2q(
506                 ((double) G.scene->r.xasp / (double) G.scene->r.yasp), 255);
507
508         set_ffmpeg_properties(c, "video");
509         
510         if (avcodec_open(c, codec) < 0) {
511                 error("Couldn't initialize codec");
512                 return NULL;
513         }
514
515         video_buffersize = 2000000;
516         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize, 
517                                              "FFMPEG video buffer");
518         
519         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
520
521         img_convert_ctx = sws_getContext(c->width, c->height,
522                                          PIX_FMT_RGBA32,
523                                          c->width, c->height,
524                                          c->pix_fmt,
525                                          SWS_BICUBIC,
526                                          NULL, NULL, NULL);
527         return st;
528 }
529
530 /* Prepare an audio stream for the output file */
531
532 static AVStream* alloc_audio_stream(int codec_id, AVFormatContext* of) 
533 {
534         AVStream* st;
535         AVCodecContext* c;
536         AVCodec* codec;
537
538         st = av_new_stream(of, 1);
539         if (!st) return NULL;
540
541         c = get_codec_from_stream(st);
542         c->codec_id = codec_id;
543         c->codec_type = CODEC_TYPE_AUDIO;
544
545         c->sample_rate = G.scene->audio.mixrate;
546         c->bit_rate = ffmpeg_audio_bitrate*1000;
547         c->channels = 2;
548         codec = avcodec_find_encoder(c->codec_id);
549         if (!codec) {
550                 error("Couldn't find a valid audio codec");
551                 return NULL;
552         }
553
554         set_ffmpeg_properties(c, "audio");
555
556         if (avcodec_open(c, codec) < 0) {
557                 error("Couldn't initialize audio codec");
558                 return NULL;
559         }
560
561         /* FIXME: Should be user configurable */
562         if (ffmpeg_type == FFMPEG_DV) {
563                 /* this is a hack around the poor ffmpeg dv multiplexer. */
564                 /* only fixes PAL for now 
565                    (NTSC is a lot more complicated here...)! */
566                 audio_outbuf_size = 7680;
567         } else {
568                 audio_outbuf_size = 10000;
569         }
570         audio_output_buffer = (uint8_t*)MEM_mallocN(
571                 audio_outbuf_size, "FFMPEG audio encoder input buffer");
572
573        /* ugly hack for PCM codecs */
574
575         if (c->frame_size <= 1) {
576                 audio_input_frame_size = audio_outbuf_size / c->channels;
577                 switch(c->codec_id) {
578                 case CODEC_ID_PCM_S16LE:
579                 case CODEC_ID_PCM_S16BE:
580                 case CODEC_ID_PCM_U16LE:
581                 case CODEC_ID_PCM_U16BE:
582                         audio_input_frame_size >>= 1;
583                         break;
584                 default:
585                         break;
586                 }
587         } else {
588                 audio_input_frame_size = c->frame_size;
589         }
590
591         audio_input_buffer = (uint8_t*)MEM_mallocN(
592                 audio_input_frame_size * sizeof(short) * c->channels, 
593                 "FFMPEG audio encoder output buffer");
594
595         return st;
596 }
597 /* essential functions -- start, append, end */
598
599 void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
600 {
601         /* Handle to the output file */
602         AVFormatContext* of;
603         AVOutputFormat* fmt;
604         char name[256];
605         const char ** exts;
606
607         ffmpeg_type = rd->ffcodecdata.type;
608         ffmpeg_codec = rd->ffcodecdata.codec;
609         ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
610         ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
611         ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
612         ffmpeg_gop_size = rd->ffcodecdata.gop_size;
613         ffmpeg_multiplex_audio = rd->ffcodecdata.flags
614                 & FFMPEG_MULTIPLEX_AUDIO;
615         ffmpeg_autosplit = rd->ffcodecdata.flags
616                 & FFMPEG_AUTOSPLIT_OUTPUT;
617         
618         do_init_ffmpeg();
619
620         /* Determine the correct filename */
621         makeffmpegstring(name);
622         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
623                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
624                 "  video_bitrate=%d, audio_bitrate=%d,\n"
625                 "  gop_size=%d, multiplex=%d, autosplit=%d\n"
626                 "  render width=%d, render height=%d\n", 
627                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
628                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
629                 ffmpeg_gop_size, ffmpeg_multiplex_audio,
630                 ffmpeg_autosplit, rectx, recty);
631         
632         exts = get_file_extensions(ffmpeg_type);
633         if (!exts) {
634                 G.afbreek = 1; /* Abort render */
635                 error("No valid formats found");
636                 return;
637         }
638         fmt = guess_format(NULL, exts[0], NULL);
639         if (!fmt) {
640                 G.afbreek = 1; /* Abort render */
641                 error("No valid formats found");
642                 return;
643         }
644
645         of = av_alloc_format_context();
646         if (!of) {
647                 G.afbreek = 1;
648                 error("Error opening output file");
649                 return;
650         }
651         
652         of->oformat = fmt;
653         of->packet_size= G.scene->r.ffcodecdata.mux_packet_size;
654         if (ffmpeg_multiplex_audio) {
655                 of->mux_rate = G.scene->r.ffcodecdata.mux_rate;
656         } else {
657                 of->mux_rate = 0;
658         }
659
660         of->preload = (int)(0.5*AV_TIME_BASE);
661         of->max_delay = (int)(0.7*AV_TIME_BASE);
662
663         snprintf(of->filename, sizeof(of->filename), "%s", name);
664         /* set the codec to the user's selection */
665         switch(ffmpeg_type) {
666         case FFMPEG_AVI:
667         case FFMPEG_MOV:
668                 fmt->video_codec = ffmpeg_codec;
669                 break;
670         case FFMPEG_DV:
671                 fmt->video_codec = CODEC_ID_DVVIDEO;
672                 break;
673         case FFMPEG_MPEG1:
674                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
675                 break;
676         case FFMPEG_MPEG2:
677                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
678                 break;
679         case FFMPEG_H264:
680                 fmt->video_codec = CODEC_ID_H264;
681                 break;
682         case FFMPEG_XVID:
683                 fmt->video_codec = CODEC_ID_XVID;
684                 break;
685         case FFMPEG_FLV:
686                 fmt->video_codec = CODEC_ID_FLV1;
687                 break;
688         case FFMPEG_MPEG4:
689         default:
690                 fmt->video_codec = CODEC_ID_MPEG4;
691                 break;
692         }
693         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
694                 if (rectx != 720) {
695                         G.afbreek = 1;
696                         error("Render width has to be 720 pixels for DV!");
697                         return;
698                 }
699                 if (G.scene->r.frs_sec != 25 && recty != 480) {
700                         G.afbreek = 1;
701                         error("Render height has to be 480 pixels "
702                               "for DV-NTSC!");
703                         return;
704                         
705                 }
706                 if (G.scene->r.frs_sec == 25 && recty != 576) {
707                         G.afbreek = 1;
708                         error("Render height has to be 576 pixels "
709                               "for DV-PAL!");
710                         return;
711                 }
712         }
713         
714         fmt->audio_codec = ffmpeg_audio_codec;
715
716         if (ffmpeg_type == FFMPEG_DV) {
717                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
718                 if (ffmpeg_multiplex_audio 
719                     && G.scene->audio.mixrate != 48000) {
720                         G.afbreek = 1;
721                         error("FFMPEG only supports 48khz / stereo "
722                               "audio for DV!");
723                         return;
724                 }
725         }
726         
727         video_stream = alloc_video_stream(fmt->video_codec, of, rectx, recty);
728         if (!video_stream) {
729                 G.afbreek = 1;
730                 error("Error initializing video stream");
731                 return;
732         }
733         
734         if (ffmpeg_multiplex_audio) {
735                 audio_stream = alloc_audio_stream(fmt->audio_codec, of);
736                 if (!audio_stream) {
737                         G.afbreek = 1;
738                         error("Error initializing audio stream");
739                         return;
740                 }
741                 audiostream_play(SFRA, 0, 1);
742         }
743         if (av_set_parameters(of, NULL) < 0) {
744                 G.afbreek = 1;
745                 error("Error setting output parameters");
746                 return;
747         }
748         if (!(fmt->flags & AVFMT_NOFILE)) {
749                 if (url_fopen(&of->pb, name, URL_WRONLY) < 0) {
750                         G.afbreek = 1;
751                         error("Could not open file for writing");
752                         return;
753                 }
754         }
755
756         av_write_header(of);
757         outfile = of;
758         dump_format(of, 0, name, 1);
759 }
760
761 /* **********************************************************************
762    * public interface
763    ********************************************************************** */
764
765 /* Get the output filename-- similar to the other output formats */
766 void makeffmpegstring(char* string) {
767         
768         char txt[FILE_MAXDIR+FILE_MAXFILE];
769         char autosplit[20];
770
771         const char ** exts = get_file_extensions(G.scene->r.ffcodecdata.type);
772         const char ** fe = exts;
773
774         if (!string || !exts) return;
775
776         strcpy(string, G.scene->r.pic);
777         BLI_convertstringcode(string, G.sce);
778         BLI_convertstringframe(string, G.scene->r.cfra);
779
780         BLI_make_existing_file(string);
781
782         autosplit[0] = 0;
783
784         if ((G.scene->r.ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
785                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
786         }
787
788         while (*fe) {
789                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
790                                    *fe) == 0) {
791                         break;
792                 }
793                 fe++;
794         }
795
796         if (!*fe) {
797                 strcat(string, autosplit);
798                 sprintf(txt, "%04d_%04d%s", (G.scene->r.sfra), 
799                         (G.scene->r.efra), *exts);
800                 strcat(string, txt);
801         } else {
802                 *(string + strlen(string) - strlen(*fe)) = 0;
803                 strcat(string, autosplit);
804                 strcat(string, *fe);
805         }
806 }
807
808
809 void start_ffmpeg(RenderData *rd, int rectx, int recty)
810 {
811         ffmpeg_autosplit_count = 0;
812
813         ffmpeg_renderdata = rd;
814
815         start_ffmpeg_impl(rd, rectx, recty);
816 }
817
818 void end_ffmpeg(void);
819
820 static void write_audio_frames()
821 {
822         int finished = 0;
823
824         while (ffmpeg_multiplex_audio && !finished) {
825                 double a_pts = ((double)audio_stream->pts.val 
826                                 * audio_stream->time_base.num 
827                                 / audio_stream->time_base.den);
828                 double v_pts = ((double)video_stream->pts.val 
829                                 * video_stream->time_base.num 
830                                 / video_stream->time_base.den);
831                 
832                 if (a_pts < v_pts) {
833                         write_audio_frame();
834                 } else {
835                         finished = 1;
836                 }
837         }
838 }
839
840 void append_ffmpeg(int frame, int *pixels, int rectx, int recty) 
841 {
842         fprintf(stderr, "Writing frame %i, "
843                 "render width=%d, render height=%d\n", frame,
844                 rectx, recty);
845
846         write_audio_frames();
847         write_video_frame(generate_video_frame((unsigned char*) pixels));
848
849         if (ffmpeg_autosplit) {
850                 if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
851                         end_ffmpeg();
852                         ffmpeg_autosplit_count++;
853                         start_ffmpeg_impl(ffmpeg_renderdata,
854                                           rectx, recty);
855                 }
856         }
857 }
858
859
860 void end_ffmpeg(void)
861 {
862         int i;
863         
864         fprintf(stderr, "Closing ffmpeg...\n");
865
866         if (audio_stream) {
867                 write_audio_frames();
868         }
869         
870         if (outfile) {
871                 av_write_trailer(outfile);
872         }
873         
874         /* Close the video codec */
875
876         if (video_stream && get_codec_from_stream(video_stream)) {
877                 avcodec_close(get_codec_from_stream(video_stream));
878                 video_stream = 0;
879         }
880
881         
882         /* Close the output file */
883         if (outfile) {
884                 for (i = 0; i < outfile->nb_streams; i++) {
885                         if (&outfile->streams[i]) {
886                                 av_freep(&outfile->streams[i]);
887                         }
888                 }
889         }
890         /* free the temp buffer */
891         if (current_frame) {
892                 delete_picture(current_frame);
893                 current_frame = 0;
894         }
895         if (outfile && outfile->oformat) {
896                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
897                         url_fclose(OUTFILE_PB);
898                 }
899         }
900         if (outfile) {
901                 av_free(outfile);
902                 outfile = 0;
903         }
904         if (video_buffer) {
905                 MEM_freeN(video_buffer);
906                 video_buffer = 0;
907         }
908         if (audio_output_buffer) {
909                 MEM_freeN(audio_output_buffer);
910                 audio_output_buffer = 0;
911         }
912         if (audio_input_buffer) {
913                 MEM_freeN(audio_input_buffer);
914                 audio_input_buffer = 0;
915         }
916
917         if (img_convert_ctx) {
918                 sws_freeContext(img_convert_ctx);
919                 img_convert_ctx = 0;
920         }
921 }
922 #endif
923