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