Welcome to mirror list, hosted at ThFree Co, Russian Federation.

writeffmpeg.c « intern « blenkernel « blender « source - git.blender.org/blender.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: ff4300c34e995577bb0710ae34bbcda393e81141 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
/*
 * ***** BEGIN GPL LICENSE BLOCK *****
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 * Contributor(s):
 *
 * Partial Copyright (c) 2006 Peter Schlaile
 *
 * ***** END GPL LICENSE BLOCK *****
 */

/** \file blender/blenkernel/intern/writeffmpeg.c
 *  \ingroup bke
 */

#ifdef WITH_FFMPEG
#include <string.h>
#include <stdio.h>

#if defined(_WIN32) && defined(DEBUG) && !defined(__MINGW32__) && !defined(__CYGWIN__)
/* This does not seem necessary or present on MSVC 8, but may be needed in earlier versions? */
#if _MSC_VER < 1400
#include <stdint.h>
#endif
#endif

#include <stdlib.h>

#include <libavformat/avformat.h>
#include <libavcodec/avcodec.h>
#include <libavutil/rational.h>
#include <libavutil/samplefmt.h>
#include <libswscale/swscale.h>

#include "MEM_guardedalloc.h"

#include "DNA_scene_types.h"

#include "BLI_blenlib.h"

#ifdef WITH_AUDASPACE
#  include "AUD_C-API.h"
#endif

#include "BLI_utildefines.h"

#include "BKE_global.h"
#include "BKE_idprop.h"
#include "BKE_main.h"
#include "BKE_report.h"
#include "BKE_sound.h"
#include "BKE_writeffmpeg.h"

#include "IMB_imbuf_types.h"
#include "IMB_imbuf.h"

#include "ffmpeg_compat.h"

static int ffmpeg_type = 0;
static int ffmpeg_codec = CODEC_ID_MPEG4;
static int ffmpeg_audio_codec = CODEC_ID_NONE;
static int ffmpeg_video_bitrate = 1150;
static int ffmpeg_audio_bitrate = 128;
static int ffmpeg_gop_size = 12;
static int ffmpeg_autosplit = 0;
static int ffmpeg_autosplit_count = 0;

static AVFormatContext *outfile = 0;
static AVStream *video_stream = 0;
static AVStream *audio_stream = 0;
static AVFrame *current_frame = 0;
static struct SwsContext *img_convert_ctx = 0;

static uint8_t *video_buffer = 0;
static int video_buffersize = 0;

static uint8_t *audio_input_buffer = 0;
static uint8_t *audio_deinterleave_buffer = 0;
static int audio_input_samples = 0;
#ifndef FFMPEG_HAVE_ENCODE_AUDIO2
static uint8_t *audio_output_buffer = 0;
static int audio_outbuf_size = 0;
#endif
static double audio_time = 0.0f;
static bool audio_deinterleave = false;
static int audio_sample_size = 0;

#ifdef WITH_AUDASPACE
static AUD_Device *audio_mixdown_device = 0;
#endif

#define FFMPEG_AUTOSPLIT_SIZE 2000000000

#define PRINT if (G.debug & G_DEBUG_FFMPEG) printf

/* Delete a picture buffer */

static void delete_picture(AVFrame *f)
{
	if (f) {
		if (f->data[0]) MEM_freeN(f->data[0]);
		av_free(f);
	}
}

static int request_float_audio_buffer(int codec_id)
{
	/* If any of these codecs, we prefer the float sample format (if supported) */
	return codec_id == CODEC_ID_AAC || codec_id == CODEC_ID_AC3 || codec_id == CODEC_ID_VORBIS;
}

#ifdef WITH_AUDASPACE
static int write_audio_frame(void) 
{
	AVCodecContext *c = NULL;
	AVPacket pkt;
	AVFrame *frame = NULL;
	int got_output = 0;

	c = audio_stream->codec;

	av_init_packet(&pkt);
	pkt.size = 0;
	pkt.data = NULL;

	AUD_readDevice(audio_mixdown_device, audio_input_buffer, audio_input_samples);
	audio_time += (double) audio_input_samples / (double) c->sample_rate;

#ifdef FFMPEG_HAVE_ENCODE_AUDIO2
	frame = avcodec_alloc_frame();
	frame->nb_samples = audio_input_samples;
	frame->format = c->sample_fmt;
#ifdef FFMPEG_HAVE_FRAME_CHANNEL_LAYOUT
	frame->channel_layout = c->channel_layout;
#endif

	if (audio_deinterleave) {
		int channel, i;
		uint8_t *temp;

		for (channel = 0; channel < c->channels; channel++) {
			for (i = 0; i < frame->nb_samples; i++) {
				memcpy(audio_deinterleave_buffer + (i + channel * frame->nb_samples) * audio_sample_size,
					   audio_input_buffer + (c->channels * i + channel) * audio_sample_size, audio_sample_size);
			}
		}

		temp = audio_deinterleave_buffer;
		audio_deinterleave_buffer = audio_input_buffer;
		audio_input_buffer = temp;
	}

	avcodec_fill_audio_frame(frame, c->channels, c->sample_fmt, audio_input_buffer,
	                         audio_input_samples * c->channels * audio_sample_size, 1);

	if (avcodec_encode_audio2(c, &pkt, frame, &got_output) < 0) {
		// XXX error("Error writing audio packet");
		return -1;
	}

	if (!got_output) {
		avcodec_free_frame(&frame);
		return 0;
	}
#else
	pkt.size = avcodec_encode_audio(c, audio_output_buffer, audio_outbuf_size, (short *) audio_input_buffer);

	if (pkt.size < 0) {
		// XXX error("Error writing audio packet");
		return -1;
	}

	pkt.data = audio_output_buffer;
	got_output = 1;
#endif

	if (got_output) {
		if (c->coded_frame && c->coded_frame->pts != AV_NOPTS_VALUE) {
			pkt.pts = av_rescale_q(c->coded_frame->pts, c->time_base, audio_stream->time_base);
			PRINT("Audio Frame PTS: %d\n", (int) pkt.pts);
		}

		pkt.stream_index = audio_stream->index;

		pkt.flags |= AV_PKT_FLAG_KEY;

		if (av_interleaved_write_frame(outfile, &pkt) != 0) {
			fprintf(stderr, "Error writing audio packet!\n");
			if (frame)
				avcodec_free_frame(&frame);
			return -1;
		}

		av_free_packet(&pkt);
	}

	if (frame)
		avcodec_free_frame(&frame);

	return 0;
}
#endif // #ifdef WITH_AUDASPACE

/* Allocate a temporary frame */
static AVFrame *alloc_picture(int pix_fmt, int width, int height)
{
	AVFrame *f;
	uint8_t *buf;
	int size;
	
	/* allocate space for the struct */
	f = avcodec_alloc_frame();
	if (!f) return NULL;
	size = avpicture_get_size(pix_fmt, width, height);
	/* allocate the actual picture buffer */
	buf = MEM_mallocN(size, "AVFrame buffer");
	if (!buf) {
		free(f);
		return NULL;
	}
	avpicture_fill((AVPicture *)f, buf, pix_fmt, width, height);
	return f;
}

/* Get the correct file extensions for the requested format,
 * first is always desired guess_format parameter */
static const char **get_file_extensions(int format)
{
	switch (format) {
		case FFMPEG_DV:
		{
			static const char *rv[] = { ".dv", NULL };
			return rv;
		}
		case FFMPEG_MPEG1:
		{
			static const char *rv[] = { ".mpg", ".mpeg", NULL };
			return rv;
		}
		case FFMPEG_MPEG2:
		{
			static const char *rv[] = { ".dvd", ".vob", ".mpg", ".mpeg", NULL };
			return rv;
		}
		case FFMPEG_MPEG4:
		{
			static const char *rv[] = { ".mp4", ".mpg", ".mpeg", NULL };
			return rv;
		}
		case FFMPEG_AVI:
		{
			static const char *rv[] = { ".avi", NULL };
			return rv;
		}
		case FFMPEG_MOV:
		{
			static const char *rv[] = { ".mov", NULL };
			return rv;
		}
		case FFMPEG_H264:
		{
			/* FIXME: avi for now... */
			static const char *rv[] = { ".avi", NULL };
			return rv;
		}

		case FFMPEG_XVID:
		{
			/* FIXME: avi for now... */
			static const char *rv[] = { ".avi", NULL };
			return rv;
		}
		case FFMPEG_FLV:
		{
			static const char *rv[] = { ".flv", NULL };
			return rv;
		}
		case FFMPEG_MKV:
		{
			static const char *rv[] = { ".mkv", NULL };
			return rv;
		}
		case FFMPEG_OGG:
		{
			static const char *rv[] = { ".ogv", ".ogg", NULL };
			return rv;
		}
		default:
			return NULL;
	}
}

/* Write a frame to the output file */
static int write_video_frame(RenderData *rd, int cfra, AVFrame *frame, ReportList *reports)
{
	int outsize = 0;
	int ret, success = 1;
	AVCodecContext *c = video_stream->codec;

	frame->pts = cfra;

	if (rd->mode & R_FIELDS) {
		frame->top_field_first = ((rd->mode & R_ODDFIELD) != 0);
	}

	outsize = avcodec_encode_video(c, video_buffer, video_buffersize,  frame);

	if (outsize > 0) {
		AVPacket packet;
		av_init_packet(&packet);

		if (c->coded_frame->pts != AV_NOPTS_VALUE) {
			packet.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_stream->time_base);
			PRINT("Video Frame PTS: %d\n", (int)packet.pts);
		}
		else {
			PRINT("Video Frame PTS: not set\n");
		}
		if (c->coded_frame->key_frame)
			packet.flags |= AV_PKT_FLAG_KEY;
		packet.stream_index = video_stream->index;
		packet.data = video_buffer;
		packet.size = outsize;
		ret = av_interleaved_write_frame(outfile, &packet);
		success = (ret == 0);
	}
	else if (outsize < 0) {
		success = 0;
	}

	if (!success)
		BKE_report(reports, RPT_ERROR, "Error writing frame");

	return success;
}

/* read and encode a frame of audio from the buffer */
static AVFrame *generate_video_frame(uint8_t *pixels, ReportList *reports)
{
	uint8_t *rendered_frame;

	AVCodecContext *c = video_stream->codec;
	int width = c->width;
	int height = c->height;
	AVFrame *rgb_frame;

	if (c->pix_fmt != PIX_FMT_BGR32) {
		rgb_frame = alloc_picture(PIX_FMT_BGR32, width, height);
		if (!rgb_frame) {
			BKE_report(reports, RPT_ERROR, "Could not allocate temporary frame");
			return NULL;
		}
	}
	else {
		rgb_frame = current_frame;
	}

	rendered_frame = pixels;

	/* Do RGBA-conversion and flipping in one step depending
	 * on CPU-Endianess */

	if (ENDIAN_ORDER == L_ENDIAN) {
		int y;
		for (y = 0; y < height; y++) {
			uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
			uint8_t *src = rendered_frame + width * 4 * y;
			uint8_t *end = src + width * 4;
			while (src != end) {
				target[3] = src[3];
				target[2] = src[2];
				target[1] = src[1];
				target[0] = src[0];

				target += 4;
				src += 4;
			}
		}
	}
	else {
		int y;
		for (y = 0; y < height; y++) {
			uint8_t *target = rgb_frame->data[0] + width * 4 * (height - y - 1);
			uint8_t *src = rendered_frame + width * 4 * y;
			uint8_t *end = src + width * 4;
			while (src != end) {
				target[3] = src[0];
				target[2] = src[1];
				target[1] = src[2];
				target[0] = src[3];

				target += 4;
				src += 4;
			}
		}
	}

	if (c->pix_fmt != PIX_FMT_BGR32) {
		sws_scale(img_convert_ctx, (const uint8_t *const *) rgb_frame->data,
		          rgb_frame->linesize, 0, c->height,
		          current_frame->data, current_frame->linesize);
		delete_picture(rgb_frame);
	}
	return current_frame;
}

static void set_ffmpeg_property_option(AVCodecContext *c, IDProperty *prop)
{
	char name[128];
	char *param;
	int fail = TRUE;

	PRINT("FFMPEG expert option: %s: ", prop->name);

	BLI_strncpy(name, prop->name, sizeof(name));

	param = strchr(name, ':');

	if (param) {
		*param++ = 0;
	}

	switch (prop->type) {
		case IDP_STRING:
			PRINT("%s.\n", IDP_String(prop));
			fail = av_opt_set(c, prop->name, IDP_String(prop), 0);
			break;
		case IDP_FLOAT:
			PRINT("%g.\n", IDP_Float(prop));
			fail = av_opt_set_double(c, prop->name, IDP_Float(prop), 0);
			break;
		case IDP_INT:
			PRINT("%d.\n", IDP_Int(prop));

			if (param) {
				if (IDP_Int(prop)) {
					fail = av_opt_set(c, name, param, 0);
				}
				else {
					return;
				}
			}
			else {
				fail = av_opt_set_int(c, prop->name, IDP_Int(prop), 0);
			}
			break;
	}

	if (fail) {
		PRINT("ffmpeg-option not supported: %s! Skipping.\n", prop->name);
	}
}

static int ffmpeg_proprty_valid(AVCodecContext *c, const char *prop_name, IDProperty *curr)
{
	int valid = 1;

	if (strcmp(prop_name, "video") == 0) {
		if (strcmp(curr->name, "bf") == 0) {
			/* flash codec doesn't support b frames */
			valid &= c->codec_id != CODEC_ID_FLV1;
		}
	}

	return valid;
}

static void set_ffmpeg_properties(RenderData *rd, AVCodecContext *c, const char *prop_name)
{
	IDProperty *prop;
	void *iter;
	IDProperty *curr;

	if (!rd->ffcodecdata.properties) {
		return;
	}
	
	prop = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, prop_name);
	if (!prop) {
		return;
	}

	iter = IDP_GetGroupIterator(prop);

	while ((curr = IDP_GroupIterNext(iter)) != NULL) {
		if (ffmpeg_proprty_valid(c, prop_name, curr))
			set_ffmpeg_property_option(c, curr);
	}
}

/* prepare a video stream for the output file */

static AVStream *alloc_video_stream(RenderData *rd, int codec_id, AVFormatContext *of,
                                    int rectx, int recty, char *error, int error_size)
{
	AVStream *st;
	AVCodecContext *c;
	AVCodec *codec;

	error[0] = '\0';

	st = avformat_new_stream(of, NULL);
	if (!st) return NULL;
	st->id = 0;

	/* Set up the codec context */
	
	c = st->codec;
	c->codec_id = codec_id;
	c->codec_type = AVMEDIA_TYPE_VIDEO;

	/* Get some values from the current render settings */
	
	c->width = rectx;
	c->height = recty;

	/* FIXME: Really bad hack (tm) for NTSC support */
	if (ffmpeg_type == FFMPEG_DV && rd->frs_sec != 25) {
		c->time_base.den = 2997;
		c->time_base.num = 100;
	}
	else if ((float) ((int) rd->frs_sec_base) == rd->frs_sec_base) {
		c->time_base.den = rd->frs_sec;
		c->time_base.num = (int) rd->frs_sec_base;
	}
	else {
		c->time_base.den = rd->frs_sec * 100000;
		c->time_base.num = ((double) rd->frs_sec_base) * 100000;
	}
	
	c->gop_size = ffmpeg_gop_size;
	c->bit_rate = ffmpeg_video_bitrate * 1000;
	c->rc_max_rate = rd->ffcodecdata.rc_max_rate * 1000;
	c->rc_min_rate = rd->ffcodecdata.rc_min_rate * 1000;
	c->rc_buffer_size = rd->ffcodecdata.rc_buffer_size * 1024;

#if 0
	/* this options are not set in ffmpeg.c and leads to artifacts with MPEG-4
	 * see #33586: Encoding to mpeg4 makes first frame(s) blocky
	 */
	c->rc_initial_buffer_occupancy = rd->ffcodecdata.rc_buffer_size * 3 / 4;
	c->rc_buffer_aggressivity = 1.0;
#endif

	c->me_method = ME_EPZS;
	
	codec = avcodec_find_encoder(c->codec_id);
	if (!codec)
		return NULL;
	
	/* Be sure to use the correct pixel format(e.g. RGB, YUV) */

	if (codec->pix_fmts) {
		c->pix_fmt = codec->pix_fmts[0];
	}
	else {
		/* makes HuffYUV happy ... */
		c->pix_fmt = PIX_FMT_YUV422P;
	}

	if (ffmpeg_type == FFMPEG_XVID) {
		/* arghhhh ... */
		c->pix_fmt = PIX_FMT_YUV420P;
		c->codec_tag = (('D' << 24) + ('I' << 16) + ('V' << 8) + 'X');
	}

	if (codec_id == CODEC_ID_H264) {
		/* correct wrong default ffmpeg param which crash x264 */
		c->qmin = 10;
		c->qmax = 51;
	}
	
	/* Keep lossless encodes in the RGB domain. */
	if (codec_id == CODEC_ID_HUFFYUV) {
		/* HUFFYUV was PIX_FMT_YUV422P before */
		c->pix_fmt = PIX_FMT_RGB32;
	}

	if (codec_id == CODEC_ID_FFV1) {
		c->pix_fmt = PIX_FMT_RGB32;
	}

	if (codec_id == CODEC_ID_QTRLE) {
		if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
			c->pix_fmt = PIX_FMT_ARGB;
		}
	}

	if (codec_id == CODEC_ID_PNG) {
		if (rd->im_format.planes == R_IMF_PLANES_RGBA) {
			c->pix_fmt = PIX_FMT_ARGB;
		}
	}

	if ((of->oformat->flags & AVFMT_GLOBALHEADER)
//		|| !strcmp(of->oformat->name, "mp4")
//	    || !strcmp(of->oformat->name, "mov")
//	    || !strcmp(of->oformat->name, "3gp")
	    )
	{
		PRINT("Using global header\n");
		c->flags |= CODEC_FLAG_GLOBAL_HEADER;
	}
	
	/* Determine whether we are encoding interlaced material or not */
	if (rd->mode & R_FIELDS) {
		PRINT("Encoding interlaced video\n");
		c->flags |= CODEC_FLAG_INTERLACED_DCT;
		c->flags |= CODEC_FLAG_INTERLACED_ME;
	}

	/* xasp & yasp got float lately... */

	st->sample_aspect_ratio = c->sample_aspect_ratio = av_d2q(((double) rd->xasp / (double) rd->yasp), 255);

	set_ffmpeg_properties(rd, c, "video");
	
	if (avcodec_open2(c, codec, NULL) < 0) {
		BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
		return NULL;
	}

	if (codec_id == CODEC_ID_QTRLE) {
		/* normally it should be enough to have buffer with actual image size,
		 * but some codecs like QTRLE might store extra information in this buffer,
		 * so it should be a way larger */

		/* maximum video buffer size is 6-bytes per pixel, plus DPX header size (1664)
		 * (from FFmpeg sources) */
		int size = c->width * c->height;
		video_buffersize = 7 * size + 10000;
	}
	else
		video_buffersize = avpicture_get_size(c->pix_fmt, c->width, c->height);

	video_buffer = (uint8_t *)MEM_mallocN(video_buffersize * sizeof(uint8_t), "FFMPEG video buffer");
	
	current_frame = alloc_picture(c->pix_fmt, c->width, c->height);

	img_convert_ctx = sws_getContext(c->width, c->height, PIX_FMT_BGR32, c->width, c->height, c->pix_fmt, SWS_BICUBIC,
	                                 NULL, NULL, NULL);
	return st;
}

static AVStream *alloc_audio_stream(RenderData *rd, int codec_id, AVFormatContext *of, char *error, int error_size)
{
	AVStream *st;
	AVCodecContext *c;
	AVCodec *codec;

	error[0] = '\0';

	st = avformat_new_stream(of, NULL);
	if (!st) return NULL;
	st->id = 1;

	c = st->codec;
	c->codec_id = codec_id;
	c->codec_type = AVMEDIA_TYPE_AUDIO;

	c->sample_rate = rd->ffcodecdata.audio_mixrate;
	c->bit_rate = ffmpeg_audio_bitrate * 1000;
	c->sample_fmt = AV_SAMPLE_FMT_S16;
	c->channels = rd->ffcodecdata.audio_channels;

	if (request_float_audio_buffer(codec_id)) {
		/* mainly for AAC codec which is experimental */
		c->strict_std_compliance = FF_COMPLIANCE_EXPERIMENTAL;
		c->sample_fmt = AV_SAMPLE_FMT_FLT;
	}

	codec = avcodec_find_encoder(c->codec_id);
	if (!codec) {
		//XXX error("Couldn't find a valid audio codec");
		return NULL;
	}

	if (codec->sample_fmts) {
		/* check if the prefered sample format for this codec is supported.
		 * this is because, depending on the version of libav, and with the whole ffmpeg/libav fork situation,
		 * you have various implementations around. float samples in particular are not always supported.
		 */
		const enum AVSampleFormat *p = codec->sample_fmts;
		for (; *p!=-1; p++) {
			if (*p == st->codec->sample_fmt)
				break;
		}
		if (*p == -1) {
			/* sample format incompatible with codec. Defaulting to a format known to work */
			st->codec->sample_fmt = codec->sample_fmts[0];
		}
	}

	if (codec->supported_samplerates) {
		const int *p = codec->supported_samplerates;
		int best = 0;
		int best_dist = INT_MAX;
		for (; *p; p++) {
			int dist = abs(st->codec->sample_rate - *p);
			if (dist < best_dist) {
				best_dist = dist;
				best = *p;
			}
		}
		/* best is the closest supported sample rate (same as selected if best_dist == 0) */
		st->codec->sample_rate = best;
	}

	set_ffmpeg_properties(rd, c, "audio");

	if (avcodec_open2(c, codec, NULL) < 0) {
		//XXX error("Couldn't initialize audio codec");
		BLI_strncpy(error, IMB_ffmpeg_last_error(), error_size);
		return NULL;
	}

	/* need to prevent floating point exception when using vorbis audio codec,
	 * initialize this value in the same way as it's done in FFmpeg iteslf (sergey) */
	st->codec->time_base.num = 1;
	st->codec->time_base.den = st->codec->sample_rate;

#ifndef FFMPEG_HAVE_ENCODE_AUDIO2
	audio_outbuf_size = FF_MIN_BUFFER_SIZE;
#endif

	if (c->frame_size == 0)
		// used to be if ((c->codec_id >= CODEC_ID_PCM_S16LE) && (c->codec_id <= CODEC_ID_PCM_DVD))
		// not sure if that is needed anymore, so let's try out if there are any
		// complaints regarding some ffmpeg versions users might have
		audio_input_samples = FF_MIN_BUFFER_SIZE * 8 / c->bits_per_coded_sample / c->channels;
	else {
		audio_input_samples = c->frame_size;
#ifndef FFMPEG_HAVE_ENCODE_AUDIO2
		if (c->frame_size * c->channels * sizeof(int16_t) * 4 > audio_outbuf_size)
			audio_outbuf_size = c->frame_size * c->channels * sizeof(int16_t) * 4;
#endif
	}

	audio_deinterleave = av_sample_fmt_is_planar(c->sample_fmt);

	audio_sample_size = av_get_bytes_per_sample(c->sample_fmt);

	audio_input_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * audio_sample_size);
#ifndef FFMPEG_HAVE_ENCODE_AUDIO2
	audio_output_buffer = (uint8_t *) av_malloc(audio_outbuf_size);
#endif

	if (audio_deinterleave)
		audio_deinterleave_buffer = (uint8_t *) av_malloc(audio_input_samples * c->channels * audio_sample_size);

	audio_time = 0.0f;

	return st;
}
/* essential functions -- start, append, end */

static void ffmpeg_dict_set_int(AVDictionary **dict, const char *key, int value)
{
	char buffer[32];

	BLI_snprintf(buffer, sizeof(buffer), "%d", value);

	av_dict_set(dict, key, buffer, 0);
}

static int start_ffmpeg_impl(struct RenderData *rd, int rectx, int recty, ReportList *reports)
{
	/* Handle to the output file */
	AVFormatContext *of;
	AVOutputFormat *fmt;
	AVDictionary *opts = NULL;
	char name[256], error[1024];
	const char **exts;

	ffmpeg_type = rd->ffcodecdata.type;
	ffmpeg_codec = rd->ffcodecdata.codec;
	ffmpeg_audio_codec = rd->ffcodecdata.audio_codec;
	ffmpeg_video_bitrate = rd->ffcodecdata.video_bitrate;
	ffmpeg_audio_bitrate = rd->ffcodecdata.audio_bitrate;
	ffmpeg_gop_size = rd->ffcodecdata.gop_size;
	ffmpeg_autosplit = rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT;
	
	/* Determine the correct filename */
	BKE_ffmpeg_filepath_get(name, rd);
	PRINT("Starting output to %s(ffmpeg)...\n"
	        "  Using type=%d, codec=%d, audio_codec=%d,\n"
	        "  video_bitrate=%d, audio_bitrate=%d,\n"
	        "  gop_size=%d, autosplit=%d\n"
	        "  render width=%d, render height=%d\n",
	        name, ffmpeg_type, ffmpeg_codec, ffmpeg_audio_codec,
	        ffmpeg_video_bitrate, ffmpeg_audio_bitrate,
	        ffmpeg_gop_size, ffmpeg_autosplit, rectx, recty);
	
	exts = get_file_extensions(ffmpeg_type);
	if (!exts) {
		BKE_report(reports, RPT_ERROR, "No valid formats found");
		return 0;
	}
	fmt = av_guess_format(NULL, exts[0], NULL);
	if (!fmt) {
		BKE_report(reports, RPT_ERROR, "No valid formats found");
		return 0;
	}

	of = avformat_alloc_context();
	if (!of) {
		BKE_report(reports, RPT_ERROR, "Error opening output file");
		return 0;
	}
	
	of->oformat = fmt;
	of->packet_size = rd->ffcodecdata.mux_packet_size;
	if (ffmpeg_audio_codec != CODEC_ID_NONE) {
		ffmpeg_dict_set_int(&opts, "muxrate", rd->ffcodecdata.mux_rate);
	}
	else {
		av_dict_set(&opts, "muxrate", "0", 0);
	}

	ffmpeg_dict_set_int(&opts, "preload", (int)(0.5 * AV_TIME_BASE));

	of->max_delay = (int)(0.7 * AV_TIME_BASE);

	fmt->audio_codec = ffmpeg_audio_codec;

	BLI_strncpy(of->filename, name, sizeof(of->filename));
	/* set the codec to the user's selection */
	switch (ffmpeg_type) {
		case FFMPEG_AVI:
		case FFMPEG_MOV:
		case FFMPEG_MKV:
			fmt->video_codec = ffmpeg_codec;
			break;
		case FFMPEG_OGG:
			fmt->video_codec = CODEC_ID_THEORA;
			break;
		case FFMPEG_DV:
			fmt->video_codec = CODEC_ID_DVVIDEO;
			break;
		case FFMPEG_MPEG1:
			fmt->video_codec = CODEC_ID_MPEG1VIDEO;
			break;
		case FFMPEG_MPEG2:
			fmt->video_codec = CODEC_ID_MPEG2VIDEO;
			break;
		case FFMPEG_H264:
			fmt->video_codec = CODEC_ID_H264;
			break;
		case FFMPEG_XVID:
			fmt->video_codec = CODEC_ID_MPEG4;
			break;
		case FFMPEG_FLV:
			fmt->video_codec = CODEC_ID_FLV1;
			break;
		case FFMPEG_MPEG4:
		default:
			fmt->video_codec = CODEC_ID_MPEG4;
			break;
	}
	if (fmt->video_codec == CODEC_ID_DVVIDEO) {
		if (rectx != 720) {
			BKE_report(reports, RPT_ERROR, "Render width has to be 720 pixels for DV!");
			return 0;
		}
		if (rd->frs_sec != 25 && recty != 480) {
			BKE_report(reports, RPT_ERROR, "Render height has to be 480 pixels for DV-NTSC!");
			return 0;
		}
		if (rd->frs_sec == 25 && recty != 576) {
			BKE_report(reports, RPT_ERROR, "Render height has to be 576 pixels for DV-PAL!");
			return 0;
		}
	}
	
	if (ffmpeg_type == FFMPEG_DV) {
		fmt->audio_codec = CODEC_ID_PCM_S16LE;
		if (ffmpeg_audio_codec != CODEC_ID_NONE && rd->ffcodecdata.audio_mixrate != 48000 && rd->ffcodecdata.audio_channels != 2) {
			BKE_report(reports, RPT_ERROR, "FFMPEG only supports 48khz / stereo audio for DV!");
			av_dict_free(&opts);
			return 0;
		}
	}
	
	if (fmt->video_codec != CODEC_ID_NONE) {
		video_stream = alloc_video_stream(rd, fmt->video_codec, of, rectx, recty, error, sizeof(error));
		PRINT("alloc video stream %p\n", video_stream);
		if (!video_stream) {
			if (error[0])
				BKE_report(reports, RPT_ERROR, error);
			else
				BKE_report(reports, RPT_ERROR, "Error initializing video stream");

			av_dict_free(&opts);
			return 0;
		}
	}

	if (ffmpeg_audio_codec != CODEC_ID_NONE) {
		audio_stream = alloc_audio_stream(rd, fmt->audio_codec, of, error, sizeof(error));
		if (!audio_stream) {
			if (error[0])
				BKE_report(reports, RPT_ERROR, error);
			else
				BKE_report(reports, RPT_ERROR, "Error initializing audio stream");
			av_dict_free(&opts);
			return 0;
		}
	}
	if (!(fmt->flags & AVFMT_NOFILE)) {
		if (avio_open(&of->pb, name, AVIO_FLAG_WRITE) < 0) {
			BKE_report(reports, RPT_ERROR, "Could not open file for writing");
			av_dict_free(&opts);
			return 0;
		}
	}
	if (avformat_write_header(of, NULL) < 0) {
		BKE_report(reports, RPT_ERROR, "Could not initialize streams, probably unsupported codec combination");
		av_dict_free(&opts);
		avio_close(of->pb);
		return 0;
	}

	outfile = of;
	av_dump_format(of, 0, name, 1);
	av_dict_free(&opts);

	return 1;
}

/**
 * Writes any delayed frames in the encoder. This function is called before 
 * closing the encoder.
 *
 * <p>
 * Since an encoder may use both past and future frames to predict 
 * inter-frames (H.264 B-frames, for example), it can output the frames 
 * in a different order from the one it was given.
 * For example, when sending frames 1, 2, 3, 4 to the encoder, it may write
 * them in the order 1, 4, 2, 3 - first the two frames used for prediction,
 * and then the bidirectionally-predicted frames. What this means in practice 
 * is that the encoder may not immediately produce one output frame for each 
 * input frame. These delayed frames must be flushed before we close the 
 * stream. We do this by calling avcodec_encode_video with NULL for the last 
 * parameter.
 * </p>
 */
static void flush_ffmpeg(void)
{
	int outsize = 0;
	int ret = 0;
	
	AVCodecContext *c = video_stream->codec;
	/* get the delayed frames */
	while (1) {
		AVPacket packet;
		av_init_packet(&packet);
		
		outsize = avcodec_encode_video(c, video_buffer, video_buffersize, NULL);
		if (outsize < 0) {
			fprintf(stderr, "Error encoding delayed frame %d\n", outsize);
			break;
		}
		if (outsize == 0) {
			break;
		}
		if (c->coded_frame->pts != AV_NOPTS_VALUE) {
			packet.pts = av_rescale_q(c->coded_frame->pts, c->time_base, video_stream->time_base);
			PRINT("Video Frame PTS: %d\n", (int) packet.pts);
		}
		else {
			PRINT("Video Frame PTS: not set\n");
		}
		if (c->coded_frame->key_frame) {
			packet.flags |= AV_PKT_FLAG_KEY;
		}
		packet.stream_index = video_stream->index;
		packet.data = video_buffer;
		packet.size = outsize;
		ret = av_interleaved_write_frame(outfile, &packet);
		if (ret != 0) {
			fprintf(stderr, "Error writing delayed frame %d\n", ret);
			break;
		}
	}
	avcodec_flush_buffers(video_stream->codec);
}

/* **********************************************************************
 * * public interface
 * ********************************************************************** */

/* Get the output filename-- similar to the other output formats */
void BKE_ffmpeg_filepath_get(char *string, RenderData *rd)
{
	char autosplit[20];

	const char **exts = get_file_extensions(rd->ffcodecdata.type);
	const char **fe = exts;

	if (!string || !exts) return;

	strcpy(string, rd->pic);
	BLI_path_abs(string, G.main->name);

	BLI_make_existing_file(string);

	autosplit[0] = 0;

	if ((rd->ffcodecdata.flags & FFMPEG_AUTOSPLIT_OUTPUT) != 0) {
		sprintf(autosplit, "_%03d", ffmpeg_autosplit_count);
	}

	if (rd->scemode & R_EXTENSION) {
		while (*fe) {
			if (BLI_strcasecmp(string + strlen(string) - strlen(*fe), *fe) == 0) {
				break;
			}
			fe++;
		}

		if (*fe == NULL) {
			strcat(string, autosplit);

			BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
			strcat(string, *exts);
		}
		else {
			*(string + strlen(string) - strlen(*fe)) = 0;
			strcat(string, autosplit);
			strcat(string, *fe);
		}
	}
	else {
		if (BLI_path_frame_check_chars(string)) {
			BLI_path_frame_range(string, rd->sfra, rd->efra, 4);
		}

		strcat(string, autosplit);
	}
}

int BKE_ffmpeg_start(struct Scene *scene, RenderData *rd, int rectx, int recty, ReportList *reports)
{
	int success;

	ffmpeg_autosplit_count = 0;

	success = start_ffmpeg_impl(rd, rectx, recty, reports);
#ifdef WITH_AUDASPACE
	if (audio_stream) {
		AVCodecContext *c = audio_stream->codec;
		AUD_DeviceSpecs specs;
		specs.channels = c->channels;

		switch (av_get_packed_sample_fmt(c->sample_fmt)) {
			case AV_SAMPLE_FMT_U8:
				specs.format = AUD_FORMAT_U8;
				break;
			case AV_SAMPLE_FMT_S16:
				specs.format = AUD_FORMAT_S16;
				break;
			case AV_SAMPLE_FMT_S32:
				specs.format = AUD_FORMAT_S32;
				break;
			case AV_SAMPLE_FMT_FLT:
				specs.format = AUD_FORMAT_FLOAT32;
				break;
			case AV_SAMPLE_FMT_DBL:
				specs.format = AUD_FORMAT_FLOAT64;
				break;
			default:
				return -31415;
		}

		specs.rate = rd->ffcodecdata.audio_mixrate;
		audio_mixdown_device = sound_mixdown(scene, specs, rd->sfra, rd->ffcodecdata.audio_volume);
#ifdef FFMPEG_CODEC_TIME_BASE
		c->time_base.den = specs.rate;
		c->time_base.num = 1;
#endif
	}
#endif
	return success;
}

static void end_ffmpeg_impl(int is_autosplit);

#ifdef WITH_AUDASPACE
static void write_audio_frames(double to_pts)
{
	int finished = 0;

	while (audio_stream && !finished) {
		if ((audio_time >= to_pts) ||
		    (write_audio_frame()))
		{
			finished = 1;
		}
	}
}
#endif

int BKE_ffmpeg_append(RenderData *rd, int start_frame, int frame, int *pixels, int rectx, int recty, ReportList *reports)
{
	AVFrame *avframe;
	int success = 1;

	PRINT("Writing frame %i, render width=%d, render height=%d\n", frame, rectx, recty);

/* why is this done before writing the video frame and again at end_ffmpeg? */
//	write_audio_frames(frame / (((double)rd->frs_sec) / rd->frs_sec_base));

	if (video_stream) {
		avframe = generate_video_frame((unsigned char *) pixels, reports);
		success = (avframe && write_video_frame(rd, frame - start_frame, avframe, reports));

		if (ffmpeg_autosplit) {
			if (avio_tell(outfile->pb) > FFMPEG_AUTOSPLIT_SIZE) {
				end_ffmpeg_impl(TRUE);
				ffmpeg_autosplit_count++;
				success &= start_ffmpeg_impl(rd, rectx, recty, reports);
			}
		}
	}

#ifdef WITH_AUDASPACE
	write_audio_frames((frame - rd->sfra) / (((double)rd->frs_sec) / (double)rd->frs_sec_base));
#endif
	return success;
}

static void end_ffmpeg_impl(int is_autosplit)
{
	unsigned int i;
	
	PRINT("Closing ffmpeg...\n");

#if 0
	if (audio_stream) { /* SEE UPPER */
		write_audio_frames();
	}
#endif

#ifdef WITH_AUDASPACE
	if (is_autosplit == FALSE) {
		if (audio_mixdown_device) {
			AUD_closeReadDevice(audio_mixdown_device);
			audio_mixdown_device = 0;
		}
	}
#endif

	if (video_stream && video_stream->codec) {
		PRINT("Flushing delayed frames...\n");
		flush_ffmpeg();
	}
	
	if (outfile) {
		av_write_trailer(outfile);
	}
	
	/* Close the video codec */

	if (video_stream && video_stream->codec) {
		avcodec_close(video_stream->codec);
		PRINT("zero video stream %p\n", video_stream);
		video_stream = 0;
	}

	
	/* Close the output file */
	if (outfile) {
		for (i = 0; i < outfile->nb_streams; i++) {
			if (&outfile->streams[i]) {
				av_freep(&outfile->streams[i]);
			}
		}
	}
	/* free the temp buffer */
	if (current_frame) {
		delete_picture(current_frame);
		current_frame = 0;
	}
	if (outfile && outfile->oformat) {
		if (!(outfile->oformat->flags & AVFMT_NOFILE)) {
			avio_close(outfile->pb);
		}
	}
	if (outfile) {
		av_free(outfile);
		outfile = 0;
	}
	if (video_buffer) {
		MEM_freeN(video_buffer);
		video_buffer = 0;
	}
	if (audio_input_buffer) {
		av_free(audio_input_buffer);
		audio_input_buffer = 0;
	}
#ifndef FFMPEG_HAVE_ENCODE_AUDIO2
	if (audio_output_buffer) {
		av_free(audio_output_buffer);
		audio_output_buffer = 0;
	}
#endif

	if (audio_deinterleave_buffer) {
		av_free(audio_deinterleave_buffer);
		audio_deinterleave_buffer = 0;
	}

	if (img_convert_ctx) {
		sws_freeContext(img_convert_ctx);
		img_convert_ctx = 0;
	}
}

void BKE_ffmpeg_end(void)
{
	end_ffmpeg_impl(FALSE);
}

/* properties */

void BKE_ffmpeg_property_del(RenderData *rd, void *type, void *prop_)
{
	struct IDProperty *prop = (struct IDProperty *) prop_;
	IDProperty *group;
	
	if (!rd->ffcodecdata.properties) {
		return;
	}

	group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
	if (group && prop) {
		IDP_FreeFromGroup(group, prop);
	}
}

IDProperty *BKE_ffmpeg_property_add(RenderData *rd, const char *type, int opt_index, int parent_index)
{
	AVCodecContext c;
	const AVOption *o;
	const AVOption *parent;
	IDProperty *group;
	IDProperty *prop;
	IDPropertyTemplate val;
	int idp_type;
	char name[256];
	
	val.i = 0;

	avcodec_get_context_defaults3(&c, NULL);

	o = c.av_class->option + opt_index;
	parent = c.av_class->option + parent_index;

	if (!rd->ffcodecdata.properties) {
		rd->ffcodecdata.properties = IDP_New(IDP_GROUP, &val, "ffmpeg"); 
	}

	group = IDP_GetPropertyFromGroup(rd->ffcodecdata.properties, type);
	
	if (!group) {
		group = IDP_New(IDP_GROUP, &val, type);
		IDP_AddToGroup(rd->ffcodecdata.properties, group);
	}

	if (parent_index) {
		BLI_snprintf(name, sizeof(name), "%s:%s", parent->name, o->name);
	}
	else {
		BLI_strncpy(name, o->name, sizeof(name));
	}

	PRINT("ffmpeg_property_add: %s %d %d %s\n", type, parent_index, opt_index, name);

	prop = IDP_GetPropertyFromGroup(group, name);
	if (prop) {
		return prop;
	}

	switch (o->type) {
		case AV_OPT_TYPE_INT:
		case AV_OPT_TYPE_INT64:
			val.i = FFMPEG_DEF_OPT_VAL_INT(o);
			idp_type = IDP_INT;
			break;
		case AV_OPT_TYPE_DOUBLE:
		case AV_OPT_TYPE_FLOAT:
			val.f = FFMPEG_DEF_OPT_VAL_DOUBLE(o);
			idp_type = IDP_FLOAT;
			break;
		case AV_OPT_TYPE_STRING:
			val.string.str = (char *)"                                                                               ";
			val.string.len = 80;
/*		val.str = (char *)"                                                                               ";*/
			idp_type = IDP_STRING;
			break;
		case AV_OPT_TYPE_CONST:
			val.i = 1;
			idp_type = IDP_INT;
			break;
		default:
			return NULL;
	}
	prop = IDP_New(idp_type, &val, name);
	IDP_AddToGroup(group, prop);
	return prop;
}

/* not all versions of ffmpeg include that, so here we go ... */

static const AVOption *my_av_find_opt(void *v, const char *name, const char *unit, int mask, int flags)
{
	AVClass *c = *(AVClass **)v;
	const AVOption *o = c->option;

	for (; o && o->name; o++) {
		if (!strcmp(o->name, name) &&
		    (!unit || (o->unit && !strcmp(o->unit, unit))) &&
		    (o->flags & mask) == flags)
		{
			return o;
		}
	}
	return NULL;
}

int BKE_ffmpeg_property_add_string(RenderData *rd, const char *type, const char *str)
{
	AVCodecContext c;
	const AVOption *o = 0;
	const AVOption *p = 0;
	char name_[128];
	char *name;
	char *param;
	IDProperty *prop = NULL;
	
	avcodec_get_context_defaults3(&c, NULL);

	strncpy(name_, str, sizeof(name_));

	name = name_;
	while (*name == ' ') name++;

	param = strchr(name, ':');

	if (!param) {
		param = strchr(name, ' ');
	}
	if (param) {
		*param++ = 0;
		while (*param == ' ') param++;
	}
	
	o = my_av_find_opt(&c, name, NULL, 0, 0);
	if (!o) {
		return 0;
	}
	if (param && o->type == AV_OPT_TYPE_CONST) {
		return 0;
	}
	if (param && o->type != AV_OPT_TYPE_CONST && o->unit) {
		p = my_av_find_opt(&c, param, o->unit, 0, 0);
		if (p) {
			prop = BKE_ffmpeg_property_add(rd, (char *) type, p - c.av_class->option, o - c.av_class->option);
		}
	}
	else {
		prop = BKE_ffmpeg_property_add(rd, (char *) type, o - c.av_class->option, 0);
	}
		

	if (!prop) {
		return 0;
	}

	if (param && !p) {
		switch (prop->type) {
			case IDP_INT:
				IDP_Int(prop) = atoi(param);
				break;
			case IDP_FLOAT:
				IDP_Float(prop) = atof(param);
				break;
			case IDP_STRING:
				strncpy(IDP_String(prop), param, prop->len);
				break;
		}
	}
	return 1;
}

static void ffmpeg_set_expert_options(RenderData *rd)
{
	int codec_id = rd->ffcodecdata.codec;

	if (rd->ffcodecdata.properties)
		IDP_FreeProperty(rd->ffcodecdata.properties);

	if (codec_id == CODEC_ID_H264) {
		/*
		 * All options here are for x264, but must be set via ffmpeg.
		 * The names are therefore different - Search for "x264 to FFmpeg option mapping"
		 * to get a list.
		 */

		/*
		 * Use CABAC coder. Using "coder:1", which should be equivalent,
		 * crashes Blender for some reason. Either way - this is no big deal.
		 */
		BKE_ffmpeg_property_add_string(rd, "video", "coder:vlc");

		/*
		 * The other options were taken from the libx264-default.preset
		 * included in the ffmpeg distribution.
		 */
//		ffmpeg_property_add_string(rd, "video", "flags:loop"); // this breaks compatibility for QT
		BKE_ffmpeg_property_add_string(rd, "video", "cmp:chroma");
		BKE_ffmpeg_property_add_string(rd, "video", "partitions:parti4x4");
		BKE_ffmpeg_property_add_string(rd, "video", "partitions:partp8x8");
		BKE_ffmpeg_property_add_string(rd, "video", "partitions:partb8x8");
		BKE_ffmpeg_property_add_string(rd, "video", "me:hex");
		BKE_ffmpeg_property_add_string(rd, "video", "subq:6");
		BKE_ffmpeg_property_add_string(rd, "video", "me_range:16");
		BKE_ffmpeg_property_add_string(rd, "video", "qdiff:4");
		BKE_ffmpeg_property_add_string(rd, "video", "keyint_min:25");
		BKE_ffmpeg_property_add_string(rd, "video", "sc_threshold:40");
		BKE_ffmpeg_property_add_string(rd, "video", "i_qfactor:0.71");
		BKE_ffmpeg_property_add_string(rd, "video", "b_strategy:1");
		BKE_ffmpeg_property_add_string(rd, "video", "bf:3");
		BKE_ffmpeg_property_add_string(rd, "video", "refs:2");
		BKE_ffmpeg_property_add_string(rd, "video", "qcomp:0.6");
		BKE_ffmpeg_property_add_string(rd, "video", "directpred:3");
		BKE_ffmpeg_property_add_string(rd, "video", "trellis:0");
		BKE_ffmpeg_property_add_string(rd, "video", "flags2:wpred");
		BKE_ffmpeg_property_add_string(rd, "video", "flags2:dct8x8");
		BKE_ffmpeg_property_add_string(rd, "video", "flags2:fastpskip");
		BKE_ffmpeg_property_add_string(rd, "video", "wpredp:2");

		if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
			BKE_ffmpeg_property_add_string(rd, "video", "cqp:0");
	}
	else if (codec_id == CODEC_ID_DNXHD) {
		if (rd->ffcodecdata.flags & FFMPEG_LOSSLESS_OUTPUT)
			BKE_ffmpeg_property_add_string(rd, "video", "mbd:rd");
	}
}

void BKE_ffmpeg_preset_set(RenderData *rd, int preset)
{
	int isntsc = (rd->frs_sec != 25);

	if (rd->ffcodecdata.properties)
		IDP_FreeProperty(rd->ffcodecdata.properties);

	switch (preset) {
		case FFMPEG_PRESET_VCD:
			rd->ffcodecdata.type = FFMPEG_MPEG1;
			rd->ffcodecdata.video_bitrate = 1150;
			rd->xsch = 352;
			rd->ysch = isntsc ? 240 : 288;
			rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
			rd->ffcodecdata.rc_max_rate = 1150;
			rd->ffcodecdata.rc_min_rate = 1150;
			rd->ffcodecdata.rc_buffer_size = 40 * 8;
			rd->ffcodecdata.mux_packet_size = 2324;
			rd->ffcodecdata.mux_rate = 2352 * 75 * 8;
			break;

		case FFMPEG_PRESET_SVCD:
			rd->ffcodecdata.type = FFMPEG_MPEG2;
			rd->ffcodecdata.video_bitrate = 2040;
			rd->xsch = 480;
			rd->ysch = isntsc ? 480 : 576;
			rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
			rd->ffcodecdata.rc_max_rate = 2516;
			rd->ffcodecdata.rc_min_rate = 0;
			rd->ffcodecdata.rc_buffer_size = 224 * 8;
			rd->ffcodecdata.mux_packet_size = 2324;
			rd->ffcodecdata.mux_rate = 0;
			break;

		case FFMPEG_PRESET_DVD:
			rd->ffcodecdata.type = FFMPEG_MPEG2;
			rd->ffcodecdata.video_bitrate = 6000;

			/* Don't set resolution, see [#21351]
			 * rd->xsch = 720;
			 * rd->ysch = isntsc ? 480 : 576; */

			rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
			rd->ffcodecdata.rc_max_rate = 9000;
			rd->ffcodecdata.rc_min_rate = 0;
			rd->ffcodecdata.rc_buffer_size = 224 * 8;
			rd->ffcodecdata.mux_packet_size = 2048;
			rd->ffcodecdata.mux_rate = 10080000;
			break;

		case FFMPEG_PRESET_DV:
			rd->ffcodecdata.type = FFMPEG_DV;
			rd->xsch = 720;
			rd->ysch = isntsc ? 480 : 576;
			break;

		case FFMPEG_PRESET_H264:
			rd->ffcodecdata.type = FFMPEG_AVI;
			rd->ffcodecdata.codec = CODEC_ID_H264;
			rd->ffcodecdata.video_bitrate = 6000;
			rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
			rd->ffcodecdata.rc_max_rate = 9000;
			rd->ffcodecdata.rc_min_rate = 0;
			rd->ffcodecdata.rc_buffer_size = 224 * 8;
			rd->ffcodecdata.mux_packet_size = 2048;
			rd->ffcodecdata.mux_rate = 10080000;

			break;

		case FFMPEG_PRESET_THEORA:
		case FFMPEG_PRESET_XVID:
			if (preset == FFMPEG_PRESET_XVID) {
				rd->ffcodecdata.type = FFMPEG_AVI;
				rd->ffcodecdata.codec = CODEC_ID_MPEG4;
			}
			else if (preset == FFMPEG_PRESET_THEORA) {
				rd->ffcodecdata.type = FFMPEG_OGG; // XXX broken
				rd->ffcodecdata.codec = CODEC_ID_THEORA;
			}

			rd->ffcodecdata.video_bitrate = 6000;
			rd->ffcodecdata.gop_size = isntsc ? 18 : 15;
			rd->ffcodecdata.rc_max_rate = 9000;
			rd->ffcodecdata.rc_min_rate = 0;
			rd->ffcodecdata.rc_buffer_size = 224 * 8;
			rd->ffcodecdata.mux_packet_size = 2048;
			rd->ffcodecdata.mux_rate = 10080000;
			break;

	}

	ffmpeg_set_expert_options(rd);
}

void BKE_ffmpeg_image_type_verify(RenderData *rd, ImageFormatData *imf)
{
	int audio = 0;

	if (imf->imtype == R_IMF_IMTYPE_FFMPEG) {
		if (rd->ffcodecdata.type <= 0 ||
		    rd->ffcodecdata.codec <= 0 ||
		    rd->ffcodecdata.audio_codec <= 0 ||
		    rd->ffcodecdata.video_bitrate <= 1)
		{
			rd->ffcodecdata.codec = CODEC_ID_MPEG2VIDEO;

			BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_DVD);
		}
		if (rd->ffcodecdata.type == FFMPEG_OGG) {
			rd->ffcodecdata.type = FFMPEG_MPEG2;
		}

		audio = 1;
	}
	else if (imf->imtype == R_IMF_IMTYPE_H264) {
		if (rd->ffcodecdata.codec != CODEC_ID_H264) {
			BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_H264);
			audio = 1;
		}
	}
	else if (imf->imtype == R_IMF_IMTYPE_XVID) {
		if (rd->ffcodecdata.codec != CODEC_ID_MPEG4) {
			BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_XVID);
			audio = 1;
		}
	}
	else if (imf->imtype == R_IMF_IMTYPE_THEORA) {
		if (rd->ffcodecdata.codec != CODEC_ID_THEORA) {
			BKE_ffmpeg_preset_set(rd, FFMPEG_PRESET_THEORA);
			audio = 1;
		}
	}

	if (audio && rd->ffcodecdata.audio_codec < 0) {
		rd->ffcodecdata.audio_codec = CODEC_ID_NONE;
		rd->ffcodecdata.audio_bitrate = 128;
	}
}

void BKE_ffmpeg_codec_settings_verify(RenderData *rd)
{
	ffmpeg_set_expert_options(rd);
}

int BKE_ffmpeg_alpha_channel_is_supported(RenderData *rd)
{
	int codec = rd->ffcodecdata.codec;

	if (codec == CODEC_ID_QTRLE)
		return TRUE;

	if (codec == CODEC_ID_PNG)
		return TRUE;

#ifdef FFMPEG_FFV1_ALPHA_SUPPORTED
	if (codec == CODEC_ID_FFV1)
		return TRUE;
#endif

	return FALSE;
}

#endif