== FFMPEG ==
[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 <libavformat/avformat.h>
33 #include <libavcodec/avcodec.h>
34 #include <libavutil/rational.h>
35 #include <libswscale/swscale.h>
36 #include <libavcodec/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         case FFMPEG_MKV: {
230                 static const char * rv[] = { ".mkv", NULL };
231                 return rv;
232         }
233         case FFMPEG_OGG: {
234                 static const char * rv[] = { ".ogg", ".ogv", NULL };
235                 return rv;
236         }
237         default:
238                 return NULL;
239         }
240 }
241
242 /* Write a frame to the output file */
243 static void write_video_frame(AVFrame* frame) 
244 {
245         int outsize = 0;
246         int ret;
247         AVCodecContext* c = get_codec_from_stream(video_stream);
248 #ifdef FFMPEG_CODEC_TIME_BASE
249         frame->pts = G.scene->r.cfra - G.scene->r.sfra;
250 #endif
251         if (G.scene->r.mode & R_FIELDS) {
252                 frame->top_field_first = ((G.scene->r.mode & R_ODDFIELD) != 0);
253         }
254
255         outsize = avcodec_encode_video(c, video_buffer, video_buffersize, 
256                                        frame);
257         if (outsize != 0) {
258                 AVPacket packet;
259                 av_init_packet(&packet);
260
261                 if (c->coded_frame->pts != AV_NOPTS_VALUE) {
262 #ifdef FFMPEG_CODEC_TIME_BASE
263                         packet.pts = av_rescale_q(c->coded_frame->pts,
264                                                   c->time_base,
265                                                   video_stream->time_base);
266 #else
267                         packet.pts = c->coded_frame->pts;
268 #endif
269                         fprintf(stderr, "Video Frame PTS: %lld\n", packet.pts);
270                 } else {
271                         fprintf(stderr, "Video Frame PTS: not set\n");
272                 }
273                 if (c->coded_frame->key_frame)
274                         packet.flags |= PKT_FLAG_KEY;
275                 packet.stream_index = video_stream->index;
276                 packet.data = video_buffer;
277                 packet.size = outsize;
278                 ret = av_interleaved_write_frame(outfile, &packet);
279         } else ret = 0;
280         if (ret != 0) {
281                 G.afbreek = 1;
282                 error("Error writing frame");
283         }
284 }
285
286 /* read and encode a frame of audio from the buffer */
287 static AVFrame* generate_video_frame(uint8_t* pixels) 
288 {
289         uint8_t* rendered_frame;
290
291         AVCodecContext* c = get_codec_from_stream(video_stream);
292         int width = c->width;
293         int height = c->height;
294         AVFrame* rgb_frame;
295
296         if (c->pix_fmt != PIX_FMT_BGR32) {
297                 rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
298                 if (!rgb_frame) {
299                         G.afbreek=1;
300                         error("Couldn't allocate temporary frame");
301                         return NULL;
302                 }
303         } else {
304                 rgb_frame = current_frame;
305         }
306
307         rendered_frame = pixels;
308
309         /* Do RGBA-conversion and flipping in one step depending
310            on CPU-Endianess */
311
312         if (G.order == L_ENDIAN) {
313                 int y;
314                 for (y = 0; y < height; y++) {
315                         uint8_t* target = rgb_frame->data[0]
316                                 + width * 4 * (height - y - 1);
317                         uint8_t* src = rendered_frame + width * 4 * y;
318                         uint8_t* end = src + width * 4;
319                         while (src != end) {
320                                 target[3] = src[3];
321                                 target[2] = src[2];
322                                 target[1] = src[1];
323                                 target[0] = src[0];
324
325                                 target += 4;
326                                 src += 4;
327                         }
328                 }
329         } else {
330                 int y;
331                 for (y = 0; y < height; y++) {
332                         uint8_t* target = rgb_frame->data[0]
333                                 + width * 4 * (height - y - 1);
334                         uint8_t* src = rendered_frame + width * 4 * y;
335                         uint8_t* end = src + width * 4;
336                         while (src != end) {
337                                 target[3] = src[0];
338                                 target[2] = src[1];
339                                 target[1] = src[2];
340                                 target[0] = src[3];
341
342                                 target += 4;
343                                 src += 4;
344                         }
345                 }
346         }
347
348         if (c->pix_fmt != PIX_FMT_BGR32) {
349                 sws_scale(img_convert_ctx, rgb_frame->data,
350                           rgb_frame->linesize, 0, c->height, 
351                           current_frame->data, current_frame->linesize);
352                 delete_picture(rgb_frame);
353         }
354         return current_frame;
355 }
356
357 static void set_ffmpeg_property_option(AVCodecContext* c, IDProperty * prop)
358 {
359         char name[128];
360         char * param;
361         const AVOption * rv = NULL;
362
363         fprintf(stderr, "FFMPEG expert option: %s: ", prop->name);
364
365         strncpy(name, prop->name, 128);
366
367         param = strchr(name, ':');
368
369         if (param) {
370                 *param++ = 0;
371         }
372
373         switch(prop->type) {
374         case IDP_STRING:
375                 fprintf(stderr, "%s.\n", IDP_String(prop));
376                 rv = av_set_string(c, prop->name, IDP_String(prop));
377                 break;
378         case IDP_FLOAT:
379                 fprintf(stderr, "%g.\n", IDP_Float(prop));
380                 rv = av_set_double(c, prop->name, IDP_Float(prop));
381                 break;
382         case IDP_INT:
383                 fprintf(stderr, "%d.\n", IDP_Int(prop));
384                 
385                 if (param) {
386                         if (IDP_Int(prop)) {
387                                 rv = av_set_string(c, name, param);
388                         } else {
389                                 return;
390                         }
391                 } else {
392                         rv = av_set_int(c, prop->name, IDP_Int(prop));
393                 }
394                 break;
395         }
396
397         if (!rv) {
398                 fprintf(stderr, "ffmpeg-option not supported: %s! Skipping.\n",
399                         prop->name);
400         }
401 }
402
403 static void set_ffmpeg_properties(AVCodecContext* c, const char * prop_name)
404 {
405         IDProperty * prop;
406         void * iter;
407         IDProperty * curr;
408
409         if (!G.scene->r.ffcodecdata.properties) {
410                 return;
411         }
412         
413         prop = IDP_GetPropertyFromGroup(
414                 G.scene->r.ffcodecdata.properties, (char*) prop_name);
415         if (!prop) {
416                 return;
417         }
418
419         iter = IDP_GetGroupIterator(prop);
420
421         while ((curr = IDP_GroupIterNext(iter)) != NULL) {
422                 set_ffmpeg_property_option(c, curr);
423         }
424 }
425
426 /* prepare a video stream for the output file */
427
428 static AVStream* alloc_video_stream(int codec_id, AVFormatContext* of,
429                                     int rectx, int recty) 
430 {
431         AVStream* st;
432         AVCodecContext* c;
433         AVCodec* codec;
434         st = av_new_stream(of, 0);
435         if (!st) return NULL;
436
437         /* Set up the codec context */
438         
439         c = get_codec_from_stream(st);
440         c->codec_id = codec_id;
441         c->codec_type = CODEC_TYPE_VIDEO;
442
443
444         /* Get some values from the current render settings */
445         
446         c->width = rectx;
447         c->height = recty;
448
449 #ifdef FFMPEG_CODEC_TIME_BASE
450         /* FIXME: Really bad hack (tm) for NTSC support */
451         if (ffmpeg_type == FFMPEG_DV && G.scene->r.frs_sec != 25) {
452                 c->time_base.den = 2997;
453                 c->time_base.num = 100;
454         } else if ((double) ((int) G.scene->r.frs_sec_base) == 
455                    G.scene->r.frs_sec_base) {
456                 c->time_base.den = G.scene->r.frs_sec;
457                 c->time_base.num = (int) G.scene->r.frs_sec_base;
458         } else {
459                 c->time_base.den = G.scene->r.frs_sec * 100000;
460                 c->time_base.num = ((double) G.scene->r.frs_sec_base) * 100000;
461         }
462 #else
463         /* FIXME: Really bad hack (tm) for NTSC support */
464         if (ffmpeg_type == FFMPEG_DV && G.scene->r.frs_sec != 25) {
465                 c->frame_rate = 2997;
466                 c->frame_rate_base = 100;
467         } else if ((double) ((int) G.scene->r.frs_sec_base) == 
468                    G.scene->r.frs_sec_base) {
469                 c->frame_rate = G.scene->r.frs_sec;
470                 c->frame_rate_base = G.scene->r.frs_sec_base;
471         } else {
472                 c->frame_rate = G.scene->r.frs_sec * 100000;
473                 c->frame_rate_base = ((double) G.scene->r.frs_sec_base)*100000;
474         }
475 #endif
476         
477         c->gop_size = ffmpeg_gop_size;
478         c->bit_rate = ffmpeg_video_bitrate*1000;
479         c->rc_max_rate = G.scene->r.ffcodecdata.rc_max_rate*1000;
480         c->rc_min_rate = G.scene->r.ffcodecdata.rc_min_rate*1000;
481         c->rc_buffer_size = G.scene->r.ffcodecdata.rc_buffer_size * 1024;
482         c->rc_initial_buffer_occupancy 
483                 = G.scene->r.ffcodecdata.rc_buffer_size*3/4;
484         c->rc_buffer_aggressivity = 1.0;
485         c->me_method = ME_EPZS;
486         
487         codec = avcodec_find_encoder(c->codec_id);
488         if (!codec) return NULL;
489         
490         /* Be sure to use the correct pixel format(e.g. RGB, YUV) */
491         
492         if (codec->pix_fmts) {
493                 c->pix_fmt = codec->pix_fmts[0];
494         } else {
495                 /* makes HuffYUV happy ... */
496                 c->pix_fmt = PIX_FMT_YUV422P;
497         }
498
499         if (codec_id == CODEC_ID_XVID) {
500                 /* arghhhh ... */
501                 c->pix_fmt = PIX_FMT_YUV420P;
502         }
503         
504         if ((of->oformat->flags & AVFMT_GLOBALHEADER)
505 //              || !strcmp(of->oformat->name, "mp4")
506 //          || !strcmp(of->oformat->name, "mov")
507 //          || !strcmp(of->oformat->name, "3gp")
508                 ) {
509                 fprintf(stderr, "Using global header\n");
510                 c->flags |= CODEC_FLAG_GLOBAL_HEADER;
511         }
512         
513         /* Determine whether we are encoding interlaced material or not */
514         if (G.scene->r.mode & R_FIELDS) {
515                 fprintf(stderr, "Encoding interlaced video\n");
516                 c->flags |= CODEC_FLAG_INTERLACED_DCT;
517                 c->flags |= CODEC_FLAG_INTERLACED_ME;
518         }
519
520         /* xasp & yasp got float lately... */
521
522         st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(
523                 ((double) G.scene->r.xasp / (double) G.scene->r.yasp), 255);
524
525         set_ffmpeg_properties(c, "video");
526         
527         if (avcodec_open(c, codec) < 0) {
528                 error("Couldn't initialize codec");
529                 return NULL;
530         }
531
532         video_buffersize = 2000000;
533         video_buffer = (uint8_t*)MEM_mallocN(video_buffersize, 
534                                              "FFMPEG video buffer");
535         
536         current_frame = alloc_picture(c->pix_fmt, c->width, c->height);
537
538         img_convert_ctx = sws_getContext(c->width, c->height,
539                                          PIX_FMT_BGR32,
540                                          c->width, c->height,
541                                          c->pix_fmt,
542                                          SWS_BICUBIC,
543                                          NULL, NULL, NULL);
544         return st;
545 }
546
547 /* Prepare an audio stream for the output file */
548
549 static AVStream* alloc_audio_stream(int codec_id, AVFormatContext* of) 
550 {
551         AVStream* st;
552         AVCodecContext* c;
553         AVCodec* codec;
554
555         st = av_new_stream(of, 1);
556         if (!st) return NULL;
557
558         c = get_codec_from_stream(st);
559         c->codec_id = codec_id;
560         c->codec_type = CODEC_TYPE_AUDIO;
561
562         c->sample_rate = G.scene->audio.mixrate;
563         c->bit_rate = ffmpeg_audio_bitrate*1000;
564         c->channels = 2;
565         codec = avcodec_find_encoder(c->codec_id);
566         if (!codec) {
567                 error("Couldn't find a valid audio codec");
568                 return NULL;
569         }
570
571         set_ffmpeg_properties(c, "audio");
572
573         if (avcodec_open(c, codec) < 0) {
574                 error("Couldn't initialize audio codec");
575                 return NULL;
576         }
577
578         /* FIXME: Should be user configurable */
579         if (ffmpeg_type == FFMPEG_DV) {
580                 /* this is a hack around the poor ffmpeg dv multiplexer. */
581                 /* only fixes PAL for now 
582                    (NTSC is a lot more complicated here...)! */
583                 audio_outbuf_size = 7680;
584         } else {
585                 audio_outbuf_size = 10000;
586         }
587         audio_output_buffer = (uint8_t*)MEM_mallocN(
588                 audio_outbuf_size, "FFMPEG audio encoder input buffer");
589
590        /* ugly hack for PCM codecs */
591
592         if (c->frame_size <= 1) {
593                 audio_input_frame_size = audio_outbuf_size / c->channels;
594                 switch(c->codec_id) {
595                 case CODEC_ID_PCM_S16LE:
596                 case CODEC_ID_PCM_S16BE:
597                 case CODEC_ID_PCM_U16LE:
598                 case CODEC_ID_PCM_U16BE:
599                         audio_input_frame_size >>= 1;
600                         break;
601                 default:
602                         break;
603                 }
604         } else {
605                 audio_input_frame_size = c->frame_size;
606         }
607
608         audio_input_buffer = (uint8_t*)MEM_mallocN(
609                 audio_input_frame_size * sizeof(short) * c->channels, 
610                 "FFMPEG audio encoder output buffer");
611
612         return st;
613 }
614 /* essential functions -- start, append, end */
615
616 void start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty)
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_multiplex_audio = rd->ffcodecdata.flags
631                 & FFMPEG_MULTIPLEX_AUDIO;
632         ffmpeg_autosplit = rd->ffcodecdata.flags
633                 & FFMPEG_AUTOSPLIT_OUTPUT;
634         
635         do_init_ffmpeg();
636
637         /* Determine the correct filename */
638         makeffmpegstring(name);
639         fprintf(stderr, "Starting output to %s(ffmpeg)...\n"
640                 "  Using type=%d, codec=%d, audio_codec=%d,\n"
641                 "  video_bitrate=%d, audio_bitrate=%d,\n"
642                 "  gop_size=%d, multiplex=%d, autosplit=%d\n"
643                 "  render width=%d, render height=%d\n", 
644                 name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
645                 ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
646                 ffmpeg_gop_size, ffmpeg_multiplex_audio,
647                 ffmpeg_autosplit, rectx, recty);
648         
649         exts = get_file_extensions(ffmpeg_type);
650         if (!exts) {
651                 G.afbreek = 1; /* Abort render */
652                 error("No valid formats found");
653                 return;
654         }
655         fmt = guess_format(NULL, exts[0], NULL);
656         if (!fmt) {
657                 G.afbreek = 1; /* Abort render */
658                 error("No valid formats found");
659                 return;
660         }
661
662         of = av_alloc_format_context();
663         if (!of) {
664                 G.afbreek = 1;
665                 error("Error opening output file");
666                 return;
667         }
668         
669         of->oformat = fmt;
670         of->packet_size= G.scene->r.ffcodecdata.mux_packet_size;
671         if (ffmpeg_multiplex_audio) {
672                 of->mux_rate = G.scene->r.ffcodecdata.mux_rate;
673         } else {
674                 of->mux_rate = 0;
675         }
676
677         of->preload = (int)(0.5*AV_TIME_BASE);
678         of->max_delay = (int)(0.7*AV_TIME_BASE);
679
680         snprintf(of->filename, sizeof(of->filename), "%s", name);
681         /* set the codec to the user's selection */
682         switch(ffmpeg_type) {
683         case FFMPEG_AVI:
684         case FFMPEG_MOV:
685         case FFMPEG_OGG:
686         case FFMPEG_MKV:
687                 fmt->video_codec = ffmpeg_codec;
688                 break;
689         case FFMPEG_DV:
690                 fmt->video_codec = CODEC_ID_DVVIDEO;
691                 break;
692         case FFMPEG_MPEG1:
693                 fmt->video_codec = CODEC_ID_MPEG1VIDEO;
694                 break;
695         case FFMPEG_MPEG2:
696                 fmt->video_codec = CODEC_ID_MPEG2VIDEO;
697                 break;
698         case FFMPEG_H264:
699                 fmt->video_codec = CODEC_ID_H264;
700                 break;
701         case FFMPEG_XVID:
702                 fmt->video_codec = CODEC_ID_XVID;
703                 break;
704         case FFMPEG_FLV:
705                 fmt->video_codec = CODEC_ID_FLV1;
706                 break;
707         case FFMPEG_MPEG4:
708         default:
709                 fmt->video_codec = CODEC_ID_MPEG4;
710                 break;
711         }
712         if (fmt->video_codec == CODEC_ID_DVVIDEO) {
713                 if (rectx != 720) {
714                         G.afbreek = 1;
715                         error("Render width has to be 720 pixels for DV!");
716                         return;
717                 }
718                 if (G.scene->r.frs_sec != 25 && recty != 480) {
719                         G.afbreek = 1;
720                         error("Render height has to be 480 pixels "
721                               "for DV-NTSC!");
722                         return;
723                         
724                 }
725                 if (G.scene->r.frs_sec == 25 && recty != 576) {
726                         G.afbreek = 1;
727                         error("Render height has to be 576 pixels "
728                               "for DV-PAL!");
729                         return;
730                 }
731         }
732         
733         fmt->audio_codec = ffmpeg_audio_codec;
734
735         if (ffmpeg_type == FFMPEG_DV) {
736                 fmt->audio_codec = CODEC_ID_PCM_S16LE;
737                 if (ffmpeg_multiplex_audio 
738                     && G.scene->audio.mixrate != 48000) {
739                         G.afbreek = 1;
740                         error("FFMPEG only supports 48khz / stereo "
741                               "audio for DV!");
742                         return;
743                 }
744         }
745         
746         video_stream = alloc_video_stream(fmt->video_codec, of, rectx, recty);
747         if (!video_stream) {
748                 G.afbreek = 1;
749                 error("Error initializing video stream");
750                 return;
751         }
752         
753         if (ffmpeg_multiplex_audio) {
754                 audio_stream = alloc_audio_stream(fmt->audio_codec, of);
755                 if (!audio_stream) {
756                         G.afbreek = 1;
757                         error("Error initializing audio stream");
758                         return;
759                 }
760                 audiostream_play(SFRA, 0, 1);
761         }
762         if (av_set_parameters(of, NULL) < 0) {
763                 G.afbreek = 1;
764                 error("Error setting output parameters");
765                 return;
766         }
767         if (!(fmt->flags & AVFMT_NOFILE)) {
768                 if (url_fopen(&of->pb, name, URL_WRONLY) < 0) {
769                         G.afbreek = 1;
770                         error("Could not open file for writing");
771                         return;
772                 }
773         }
774
775         av_write_header(of);
776         outfile = of;
777         dump_format(of, 0, name, 1);
778 }
779
780 /* **********************************************************************
781    * public interface
782    ********************************************************************** */
783
784 /* Get the output filename-- similar to the other output formats */
785 void makeffmpegstring(char* string) {
786         
787         char txt[FILE_MAXDIR+FILE_MAXFILE];
788         char autosplit[20];
789
790         const char ** exts = get_file_extensions(G.scene->r.ffcodecdata.type);
791         const char ** fe = exts;
792
793         if (!string || !exts) return;
794
795         strcpy(string, G.scene->r.pic);
796         BLI_convertstringcode(string, G.sce);
797         BLI_convertstringframe(string, G.scene->r.cfra);
798
799         BLI_make_existing_file(string);
800
801         autosplit[0] = 0;
802
803         if ((G.scene->r.ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
804                 sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
805         }
806
807         while (*fe) {
808                 if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), 
809                                    *fe) == 0) {
810                         break;
811                 }
812                 fe++;
813         }
814
815         if (!*fe) {
816                 strcat(string, autosplit);
817                 sprintf(txt, "%04d_%04d%s", (G.scene->r.sfra), 
818                         (G.scene->r.efra), *exts);
819                 strcat(string, txt);
820         } else {
821                 *(string + strlen(string) - strlen(*fe)) = 0;
822                 strcat(string, autosplit);
823                 strcat(string, *fe);
824         }
825 }
826
827
828 void start_ffmpeg(RenderData *rd, int rectx, int recty)
829 {
830         ffmpeg_autosplit_count = 0;
831
832         ffmpeg_renderdata = rd;
833
834         start_ffmpeg_impl(rd, rectx, recty);
835 }
836
837 void end_ffmpeg(void);
838
839 static void write_audio_frames()
840 {
841         int finished = 0;
842
843         while (ffmpeg_multiplex_audio && !finished) {
844                 double a_pts = ((double)audio_stream->pts.val 
845                                 * audio_stream->time_base.num 
846                                 / audio_stream->time_base.den);
847                 double v_pts = ((double)video_stream->pts.val 
848                                 * video_stream->time_base.num 
849                                 / video_stream->time_base.den);
850                 
851                 if (a_pts < v_pts) {
852                         write_audio_frame();
853                 } else {
854                         finished = 1;
855                 }
856         }
857 }
858
859 void append_ffmpeg(int frame, int *pixels, int rectx, int recty) 
860 {
861         fprintf(stderr, "Writing frame %i, "
862                 "render width=%d, render height=%d\n", frame,
863                 rectx, recty);
864
865         write_audio_frames();
866         write_video_frame(generate_video_frame((unsigned char*) pixels));
867
868         if (ffmpeg_autosplit) {
869                 if (url_ftell(OUTFILE_PB) > FFMPEG_AUTOSPLIT_SIZE) {
870                         end_ffmpeg();
871                         ffmpeg_autosplit_count++;
872                         start_ffmpeg_impl(ffmpeg_renderdata,
873                                           rectx, recty);
874                 }
875         }
876 }
877
878
879 void end_ffmpeg(void)
880 {
881         int i;
882         
883         fprintf(stderr, "Closing ffmpeg...\n");
884
885         if (audio_stream && video_stream) {
886                 write_audio_frames();
887         }
888         
889         if (outfile) {
890                 av_write_trailer(outfile);
891         }
892         
893         /* Close the video codec */
894
895         if (video_stream && get_codec_from_stream(video_stream)) {
896                 avcodec_close(get_codec_from_stream(video_stream));
897                 video_stream = 0;
898         }
899
900         
901         /* Close the output file */
902         if (outfile) {
903                 for (i = 0; i < outfile->nb_streams; i++) {
904                         if (&outfile->streams[i]) {
905                                 av_freep(&outfile->streams[i]);
906                         }
907                 }
908         }
909         /* free the temp buffer */
910         if (current_frame) {
911                 delete_picture(current_frame);
912                 current_frame = 0;
913         }
914         if (outfile && outfile->oformat) {
915                 if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
916                         url_fclose(OUTFILE_PB);
917                 }
918         }
919         if (outfile) {
920                 av_free(outfile);
921                 outfile = 0;
922         }
923         if (video_buffer) {
924                 MEM_freeN(video_buffer);
925                 video_buffer = 0;
926         }
927         if (audio_output_buffer) {
928                 MEM_freeN(audio_output_buffer);
929                 audio_output_buffer = 0;
930         }
931         if (audio_input_buffer) {
932                 MEM_freeN(audio_input_buffer);
933                 audio_input_buffer = 0;
934         }
935
936         if (img_convert_ctx) {
937                 sws_freeContext(img_convert_ctx);
938                 img_convert_ctx = 0;
939         }
940 }
941 #endif
942