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