summaryrefslogtreecommitdiff
path: root/video/quicktime_recorder.cpp
blob: 9ed476658d59feab0973baef4cab9720b8a66db4 (plain) (blame)
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
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
//========= Copyright Valve Corporation, All rights reserved. ============//
//
//----------------------------------------------------------------------------------------

#define WIN32_LEAN_AND_MEAN

#include "quicktime_recorder.h"
#include "filesystem.h"

#ifdef _WIN32
	#include "windows.h"
#endif

//-----------------------------------------------------------------------------

//-----------------------------------------------------------------------------

#define SAFE_DISPOSE_HANDLE( _handle )		if ( _handle != nullptr ) { DisposeHandle( (Handle) _handle ); _handle = nullptr; }
#define SAFE_DISPOSE_GWORLD( _gworld )		if ( _gworld != nullptr ) { DisposeGWorld( _gworld ); _gworld = nullptr; }
#define SAFE_DISPOSE_MOVIE( _movie )		if ( _movie != nullptr ) { DisposeMovie( _movie ); ThreadSleep(10); Assert( GetMoviesError() == noErr ); _movie = nullptr; }


// Platform check
#if defined ( OSX ) || defined ( WIN32 )
	// platform is supported
#else	
	#error "Unsupported Platform for QuickTime"
#endif



//-----------------------------------------------------------------------------
// Helper functions for copying and converting bitmaps
//-----------------------------------------------------------------------------
enum PixelComponent_t
{
	RED = 0,
	GREEN,
	BLUE,
	ALPHA
};


int GetBytesPerPixel( OSType pixelFormat )
{
	int bpp = ( pixelFormat == k24BGRPixelFormat || pixelFormat == k24RGBPixelFormat ) ? 3 : 
			  ( pixelFormat == k32BGRAPixelFormat || pixelFormat == k32RGBAPixelFormat ) ? 4 : 0;
			  
	Assert( bpp > 0 );
	return bpp;
}


int GetPixelCompnentByteOffset( OSType format, PixelComponent_t component )
{
	if ( component == RED )
	{
		return ( format == k24RGBPixelFormat || format == k32RGBAPixelFormat ) ? 0 :
			   ( format == k24BGRPixelFormat || format == k32BGRAPixelFormat ) ? 2 : -1;
	}
	if ( component == GREEN )
	{
		return ( format == k24RGBPixelFormat || format == k32RGBAPixelFormat ) ? 1 :
			   ( format == k24BGRPixelFormat || format == k32BGRAPixelFormat ) ? 1 : -1;
	}
	if ( component == BLUE )
	{
		return ( format == k24RGBPixelFormat || format == k32RGBAPixelFormat ) ? 2 :
			   ( format == k24BGRPixelFormat || format == k32BGRAPixelFormat ) ? 0 : -1;
	}
	if ( component == ALPHA )
	{
		return ( format == k32BGRAPixelFormat || format == k32RGBAPixelFormat ) ? 3 : -1;
	}

	Assert( false );
	return -1;
}


bool CopyBitMapPixels( int width, int height, OSType srcFmt, byte *srcBase, int srcStride, OSType dstFmt, byte *dstBase, int dstStride )
{
	AssertExitF( width > 0 && height > 0 && srcBase != nullptr && srcStride > 0 && dstBase != nullptr && dstStride > 0 );
	
	// copy the bitmap pixels into our GWorld
	if ( srcFmt == dstFmt )		// identical formats, memcopy each line
	{
		int srcLineSize = width * GetBytesPerPixel( srcFmt );
		AssertExitF( srcLineSize <= dstStride && srcLineSize <= srcStride );
		
		for ( int y = 0; y < height; y++ )
		{
			byte *src = srcBase + srcStride * y;
			byte *dst = dstBase + dstStride * y;
			memcpy( dst, src, srcLineSize );
		}
		
		return true;
	}

	// ok, we got some byte swizzling to do.. get the info we need	
	int srcBPP = GetBytesPerPixel( srcFmt );
	int dstBPP = GetBytesPerPixel( dstFmt );

	int rSrcIndex = GetPixelCompnentByteOffset( srcFmt, RED );
	int gSrcIndex = GetPixelCompnentByteOffset( srcFmt, GREEN );
	int bSrcIndex = GetPixelCompnentByteOffset( srcFmt, BLUE );
	int aSrcIndex = GetPixelCompnentByteOffset( srcFmt, ALPHA );
	
	int rDstIndex = GetPixelCompnentByteOffset( dstFmt, RED );
	int gDstIndex = GetPixelCompnentByteOffset( dstFmt, GREEN );
	int bDstIndex = GetPixelCompnentByteOffset( dstFmt, BLUE );
	int aDstIndex = GetPixelCompnentByteOffset( dstFmt, ALPHA );

	Assert( rSrcIndex >= 0 && gSrcIndex >= 0 && bSrcIndex >= 0 );
	
	// 3 byte format to 3 byte format or a 4 byte format to a 3 byte format?
	if ( dstBPP == 3 )
	{
		for ( int y = 0; y < height; y++ )
		{
			byte *src = srcBase + srcStride * y;
			byte *dst = dstBase + dstStride * y;
			
			for ( int x = 0; x < width; x++, dst+=dstBPP, src+=srcBPP )
			{
				dst[rDstIndex] = src[rSrcIndex];
				dst[gDstIndex] = src[gSrcIndex];
				dst[bDstIndex] = src[bSrcIndex];
			}
		}
		return true;
	}

	AssertExitF( aDstIndex >= 0 );
	
	// 3 byte format to 4 byte format?
	if ( srcBPP == 3 && dstBPP == 4 )
	{
		for ( int y = 0; y < height; y++ )
		{
			byte *src = srcBase + srcStride * y;
			byte *dst = dstBase + dstStride * y;
			
			for ( int x = 0; x < width; x++, dst+=dstBPP, src+=srcBPP )
			{
				dst[rDstIndex] = src[rSrcIndex];
				dst[gDstIndex] = src[gSrcIndex];
				dst[bDstIndex] = src[bSrcIndex];
				dst[aDstIndex] = 0xFF;
			}
		}
		return true;
	}
	
	// 4 byte format to 4 byte format?
	if ( srcBPP == 4 && dstBPP == 4 )
	{
		for ( int y = 0; y < height; y++ )
		{
			byte *src = srcBase + srcStride * y;
			byte *dst = dstBase + dstStride * y;
			
			for ( int x = 0; x < width; x++, dst+=dstBPP, src+=srcBPP )
			{
				dst[rDstIndex] = src[rSrcIndex];
				dst[gDstIndex] = src[gSrcIndex];
				dst[bDstIndex] = src[bSrcIndex];
				dst[aDstIndex] = src[aSrcIndex];
			}
		}
		return true;
	}

	// didn't find the format?
	Assert( false );
	return false;
}



//-----------------------------------------------------------------------------
// Utility functions to save targa images
//-----------------------------------------------------------------------------
#pragma pack( push, 1 )
struct TGA_Header
{
   public:
	byte  identsize;          // size of ID field that follows 18 byte header (0 usually)
	byte  colourmaptype;      // type of colour map 0=none, 1=has palette
	byte  imagetype;          // type of image 0=none,1=indexed,2=rgb,3=grey,+8=rle packed

	short colourmapstart;     // first colour map entry in palette
	short colourmaplength;    // number of colours in palette
	byte  colourmapbits;      // number of bits per palette entry 15,16,24,32

	short xstart;             // image x origin
	short ystart;             // image y origin
	short width;              // image width in pixels
	short height;             // image height in pixels
	byte  bits;               // image bits per pixel 8,16,24,32
	byte  descriptor;         // image descriptor bits (vh flip bits)

	// pixel data follows header
};
#pragma pack(pop)



void SaveToTargaFile( int frameNum, const char* pBaseFileName, int width, int height, void *pPixels, OSType PixelFormat, int strideAdjust )	
{
	if ( pBaseFileName == nullptr || pPixels== nullptr ) return;

	Assert( sizeof( TGA_Header ) == 18 );
	
	TGA_Header  theHeader;
	ZeroVar( theHeader );

	int BytesPerPixel = GetBytesPerPixel( PixelFormat );
	Assert( BytesPerPixel > 0 );

	theHeader.imagetype = 2;
	theHeader.width = (short) width;
	theHeader.height = (short) height;
	theHeader.colourmapbits = BytesPerPixel * 8;
	theHeader.bits = BytesPerPixel * 8;
	theHeader.descriptor = ( BytesPerPixel == 4) ? ( 8 | 32 ) : 32;		// Targa32, Upper Left Origin, attribute (alpha) bits in bits 0-3

	char TGAFileName[MAX_PATH];
	
	V_snprintf( TGAFileName, MAX_PATH, "%s%.4d.tga", pBaseFileName, frameNum );

	FileHandle_t TGAFile = g_pFullFileSystem->Open( TGAFileName, "wb" );

	g_pFullFileSystem->Write( &theHeader, sizeof( theHeader ), TGAFile );
	
	// is the buffer in BGR format?
	if ( PixelFormat == k24BGRPixelFormat || PixelFormat == k32BGRAPixelFormat )
	{
		if ( strideAdjust == 0 )
		{
			g_pFullFileSystem->Write( pPixels, width * height * BytesPerPixel, TGAFile );
		}
		else
		{
			int lineWidth = width * BytesPerPixel;
			int lineOffset = lineWidth + strideAdjust;
			for ( int y = 0; y < height; y++ )
			{
				byte *pData = (byte*) pPixels + ( y * lineOffset );
				g_pFullFileSystem->Write( pData, lineWidth, TGAFile );
			}
		}
	
	}
	else	// we need to convert the bits from RGB to BGR
	{
		byte *pData = new byte[width * height * BytesPerPixel];

		OSType tgaFormat = ( PixelFormat == k24RGBPixelFormat ) ? k24BGRPixelFormat :
						   ( PixelFormat == k32RGBAPixelFormat ) ? k32BGRAPixelFormat : 0;
						   
		CopyBitMapPixels( width, height, PixelFormat, (byte*) pPixels, width * BytesPerPixel + strideAdjust, tgaFormat, pData, width * BytesPerPixel );
		
		g_pFullFileSystem->Write( pData, width * height * BytesPerPixel, TGAFile );
		
		delete [] pData;	
	}
	
	g_pFullFileSystem->Close( TGAFile );
	
}




// ===========================================================================
// Data tables used to estimate file size
// ===========================================================================
enum EstVideoEncodeQuality_t
{
	cVEQuality_Min = 0,
	cVEQuality_Low = 25,
	cVEQuality_Normal = 50,
	cVEQuality_High = 75,
	cVEQuality_Max = 100
};


struct EncodingDataRateInfo_t
{
		EstVideoEncodeQuality_t		m_QualitySetting;
		int							m_XResolution;
		int							m_YResolution;		
		float						m_DataRate;			// in MBits / second
};


struct VideoRes_t
{
	int		X, Y;
};


static EstVideoEncodeQuality_t s_QualityPresets[] =
{
	cVEQuality_Min,
	cVEQuality_Low,
	cVEQuality_Normal,
	cVEQuality_High,
	cVEQuality_Max
};


static VideoRes_t s_ResolutionPresets[] =
{
	{  16, 16  },
	{ 720, 480 },
	{ 640, 960 },
	{ 960, 640 },
	{ 1280, 720 },
	{ 1920, 1080 },
	{ 2048, 2048 },
};


static EncodingDataRateInfo_t  s_H264EncodeRates[] = 
{
	{ cVEQuality_Min,   16,  160, 2.00f },
	{ cVEQuality_Min,  720,  480, 2.26f },
	{ cVEQuality_Min,  640,  960, 2.73f },
	{ cVEQuality_Min,  960,  640, 2.91f },
	{ cVEQuality_Min, 1280,  720, 3.56f },
	{ cVEQuality_Min, 1920, 1080, 5.6f },
	{ cVEQuality_Min, 2048, 2048, 6.6f },
	
	{ cVEQuality_Low,   16,  160, 3.00f },
	{ cVEQuality_Low,  720,  480, 3.65f },
	{ cVEQuality_Low,  640,  960, 4.57f },
	{ cVEQuality_Low,  960,  640, 5.03f },
	{ cVEQuality_Low, 1280,  720, 6.41f },
	{ cVEQuality_Low, 1920, 1080, 10.57f },
	{ cVEQuality_Low, 2048, 2048, 13.0f },

	{ cVEQuality_Normal,   16,  160, 5.00f },
	{ cVEQuality_Normal,  720,  480, 6.4f },
	{ cVEQuality_Normal,  640,  960, 8.25f },
	{ cVEQuality_Normal,  960,  640, 9.24f },
	{ cVEQuality_Normal, 1280,  720, 12.1f },
	{ cVEQuality_Normal, 1920, 1080, 20.64f },
	{ cVEQuality_Normal, 2048, 2048, 25.0f },

	{ cVEQuality_High,   16,  160, 9.50f },
	{ cVEQuality_High,  720,  480, 11.3f },
	{ cVEQuality_High,  640,  960, 15.06f },
	{ cVEQuality_High,  960,  640, 16.9f },
	{ cVEQuality_High, 1280,  720, 22.72 },
	{ cVEQuality_High, 1920, 1080, 40.06f },
	{ cVEQuality_High, 2048, 2048, 52.5f },

	{ cVEQuality_Max,   16,  160, 15.50f },
	{ cVEQuality_Max,  720,  480, 19.33f },
	{ cVEQuality_Max,  640,  960, 29.89f },
	{ cVEQuality_Max,  960,  640, 26.82f },
	{ cVEQuality_Max, 1280,  720, 41.08f },
	{ cVEQuality_Max, 1920, 1080, 75.14f },
	{ cVEQuality_Max, 2048, 2048, 90.0f },

};




// ===========================================================================
// CQuickTimeVideoRecorder class - implements IVideoRecorder interface for
//     QuickTime, and buffers commands to the actual encoder object
// ===========================================================================
CQuickTimeVideoRecorder::CQuickTimeVideoRecorder() :
	m_pEncoder( nullptr ),
	m_LastResult( VideoResult::SUCCESS ),
	m_bHasAudio( false ),
	m_bMovieFinished( false )
{

}


CQuickTimeVideoRecorder::~CQuickTimeVideoRecorder()
{
	if ( m_pEncoder != nullptr )
	{
		// Abort any encoding in progress
		if ( !m_bMovieFinished )
		{
			AbortMovie();
		}
		SAFE_DELETE( m_pEncoder );
	}
}


bool CQuickTimeVideoRecorder::CreateNewMovieFile( const char *pFilename, bool hasAudio )
{
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_NOT_EMPTY( pFilename ) );

	SetResult( VideoResult::OPERATION_ALREADY_PERFORMED );
	AssertExitF( m_pEncoder == nullptr  && !m_bMovieFinished );
	
	// Create new video recorder
	m_pEncoder = new CQTVideoFileComposer();
	if ( !m_pEncoder->CreateNewMovie( pFilename, hasAudio ) )
	{
		SetResult( m_pEncoder->GetResult() );	// save the error result for after the encoder goes poof
		SAFE_DELETE( m_pEncoder );
		return false;
	}

	m_bHasAudio = hasAudio;

	SetResult( VideoResult::SUCCESS );
	return true;
}


bool CQuickTimeVideoRecorder::SetMovieVideoParameters( VideoEncodeCodec_t theCodec, int videoQuality, int movieFrameWidth, int movieFrameHeight, VideoFrameRate_t movieFPS, VideoEncodeGamma_t gamma )
{
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGECOUNT( theCodec, VideoEncodeCodec::DEFAULT_CODEC, VideoEncodeCodec::CODEC_COUNT ) );
	AssertExitF( IS_IN_RANGE( videoQuality, VideoEncodeQuality::MIN_QUALITY, VideoEncodeQuality::MAX_QUALITY ) );
	AssertExitF( IS_IN_RANGE( movieFrameWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( movieFrameHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
	AssertExitF( IS_IN_RANGE( movieFPS.GetFPS(), cMinFPS, cMaxFPS ) );
	AssertExitF( IS_IN_RANGECOUNT( gamma, VideoEncodeGamma::NO_GAMMA_ADJUST, VideoEncodeGamma::GAMMA_COUNT ) );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );

	return m_pEncoder->SetMovieVideoParameters( movieFrameWidth, movieFrameHeight, movieFPS, theCodec, videoQuality, gamma );
}


bool CQuickTimeVideoRecorder::SetMovieSourceImageParameters( VideoEncodeSourceFormat_t srcImageFormat, int imgWidth, int imgHeight )
{
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGECOUNT( srcImageFormat, VideoEncodeSourceFormat::VIDEO_FORMAT_FIRST, VideoEncodeSourceFormat::VIDEO_FORMAT_COUNT ) );
	AssertExitF( IS_IN_RANGE( imgWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( imgHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );

	return m_pEncoder->SetMovieSourceImageParameters( imgWidth, imgHeight, srcImageFormat );
}


bool CQuickTimeVideoRecorder::SetMovieSourceAudioParameters( AudioEncodeSourceFormat_t srcAudioFormat, int audioSampleRate, AudioEncodeOptions_t audioOptions, int audioSampleGroupSize )
{
	SetResult( VideoResult::ILLEGAL_OPERATION );
	AssertExitF( m_bHasAudio );

	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGECOUNT( srcAudioFormat, AudioEncodeSourceFormat::AUDIO_NONE, AudioEncodeSourceFormat::AUDIO_FORMAT_COUNT ) );
	AssertExitF( audioSampleRate == 0 || IS_IN_RANGE( audioSampleRate, cMinSampleRate, cMaxSampleRate ) );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );

	bool result = m_pEncoder->SetMovieSourceAudioParameters( srcAudioFormat, audioSampleRate, audioOptions, audioSampleGroupSize );
	
	m_bHasAudio = m_pEncoder->HasAudio();	// Audio can be turned off after specifying, so reload status
	return result;
}


bool CQuickTimeVideoRecorder::IsReadyToRecord()
{
	return ( m_pEncoder == nullptr || m_bMovieFinished ) ? false : m_pEncoder->IsReadyToRecord();
}
 
 
VideoResult_t CQuickTimeVideoRecorder::GetLastResult()
{
	return  ( m_pEncoder == nullptr ) ? m_LastResult : m_pEncoder->GetResult();
}


void CQuickTimeVideoRecorder::SetResult( VideoResult_t resultCode )
{
	m_LastResult = resultCode;
	if ( m_pEncoder != nullptr )
	{
		m_pEncoder->SetResult( resultCode );
	}
}


bool CQuickTimeVideoRecorder::AppendVideoFrame( void *pFrameBuffer, int nStrideAdjustBytes )
{
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( pFrameBuffer != nullptr );
	
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( IsReadyToRecord() );
	
	return m_pEncoder->AppendVideoFrameToMedia( pFrameBuffer, nStrideAdjustBytes );
}


bool CQuickTimeVideoRecorder::AppendAudioSamples( void *pSampleBuffer, size_t sampleSize )
{
	SetResult( VideoResult::ILLEGAL_OPERATION );
	AssertExitF( m_bHasAudio );
	
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( pSampleBuffer != nullptr );
	
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( IsReadyToRecord() );

	return m_pEncoder->AppendAudioSamplesToMedia( pSampleBuffer, sampleSize );
}


int CQuickTimeVideoRecorder::GetFrameCount()
{
	return ( m_pEncoder == nullptr ) ? 0 : m_pEncoder->GetFrameCount();
}


int CQuickTimeVideoRecorder::GetSampleCount()
{
	return ( m_pEncoder == nullptr ) ? 0 : m_pEncoder->GetSampleCount();
}


VideoFrameRate_t CQuickTimeVideoRecorder::GetFPS()
{
	return ( m_pEncoder == nullptr ) ? VideoFrameRate_t( 0 ) : m_pEncoder->GetFPS();
}


int CQuickTimeVideoRecorder::GetSampleRate()
{
	return ( m_pEncoder == nullptr ) ? 0 : m_pEncoder->GetSampleRate();
}


bool CQuickTimeVideoRecorder::AbortMovie()
{
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );

	m_bMovieFinished = true;
	return m_pEncoder->AbortMovie();
}


bool CQuickTimeVideoRecorder::FinishMovie( bool SaveMovieToDisk )
{
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_pEncoder != nullptr && !m_bMovieFinished );

	m_bMovieFinished = true;
	return m_pEncoder->FinishMovie( SaveMovieToDisk );
}


#ifdef ENABLE_EXTERNAL_ENCODER_LOGGING
bool CQuickTimeVideoRecorder::LogMessage( const char *pMsg )
{
	if ( m_pEncoder != nullptr )
	{
		m_pEncoder->LogMessage( pMsg );
	}

	return true;
}
#endif

bool CQuickTimeVideoRecorder::EstimateMovieFileSize( size_t *pEstSize, int movieWidth, int movieHeight, VideoFrameRate_t movieFps, float movieDuration, VideoEncodeCodec_t theCodec, int videoQuality,  AudioEncodeSourceFormat_t srcAudioFormat, int audioSampleRate )
{
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertPtrExitF( pEstSize );
	*pEstSize = 0;

	AssertExitF( IS_IN_RANGE( movieWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( movieHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
	AssertExitF( IS_IN_RANGE( movieFps.GetFPS(), cMinFPS, cMaxFPS ) && movieDuration > 0.0f );
	AssertExitF( IS_IN_RANGECOUNT( theCodec, VideoEncodeCodec::DEFAULT_CODEC, VideoEncodeCodec::CODEC_COUNT ) );
	AssertExitF( IS_IN_RANGE( videoQuality, VideoEncodeQuality::MIN_QUALITY, VideoEncodeQuality::MAX_QUALITY ) );
	AssertExitF( IS_IN_RANGECOUNT( srcAudioFormat, AudioEncodeSourceFormat::AUDIO_NONE, AudioEncodeSourceFormat::AUDIO_FORMAT_COUNT ) );
	AssertExitF( audioSampleRate == 0 || IS_IN_RANGE( audioSampleRate, cMinSampleRate, cMaxSampleRate ) );

	// Determine the Quality LERP
	int  Q1 = VideoEncodeQuality::MIN_QUALITY, Q2 = VideoEncodeQuality::MAX_QUALITY;
	float  Qlerp = 0.0f;
	bool   bQLerp = true;
	
	for ( int i = 0; i < ARRAYSIZE( s_QualityPresets ); i++ )
	{
		if ( s_QualityPresets[i] == videoQuality )
		{
			Q1 = videoQuality;
			Q2 = videoQuality;
			Qlerp = 0.0f;
			bQLerp = false;
			break;
		}
		else if ( s_QualityPresets[i] < videoQuality && s_QualityPresets[i] > Q1 )
		{
			Q1 = s_QualityPresets[i];
		}
		else if ( s_QualityPresets[i] > videoQuality && s_QualityPresets[i] < Q2 )
		{
			Q2 = s_QualityPresets[i];
		}
	}
	
	if ( bQLerp )
	{
		Qlerp =  ( (float) videoQuality - (float) Q1 ) / ( (float) Q2 - (float) Q1 ) ;
	}
	
	// determine the resolution lerp
	
	VideoRes_t		RES1 = { cMinVideoFrameWidth, cMinVideoFrameHeight }, RES2 = { cMaxVideoFrameWidth, cMaxVideoFrameHeight };
	float			RLerp = 0.0f;
	bool			bRLerp = true;
	int				nPixels = movieHeight * movieWidth;
	int				R1pixels = RES1.X * RES1.Y;
	int				R2pixels = RES2.X * RES2.Y;

	for ( int i = 0; i < ARRAYSIZE( s_ResolutionPresets ); i++ )
	{
		if ( s_ResolutionPresets[i].X == movieWidth && s_ResolutionPresets[i].Y == movieHeight )
		{
			RES1 = s_ResolutionPresets[i]; 
			RES2 = s_ResolutionPresets[i]; 
			RLerp = 0.0f;
			bRLerp = false;
			break;
		}
	
		int rPixels = s_ResolutionPresets[i].X * s_ResolutionPresets[i].Y;
		
		if ( rPixels <= nPixels && rPixels > R1pixels )
		{
			RES1 = s_ResolutionPresets[i];
			R1pixels = rPixels;
		}
		else if ( rPixels > nPixels && rPixels < R2pixels )
		{
			RES2 = s_ResolutionPresets[i];
			R2pixels = rPixels;
		}
	}
	
	if ( bRLerp )
	{
		RLerp = (float) (nPixels - R1pixels) / (float) ( R2pixels - R1pixels );
	}
	

	// Now we see what we need to do
	// We determine the estimated Data Rate
	
	float DR = 0.0f;
	
	if ( bQLerp == false && bRLerp == false )
	{
		DR = GetDataRate( videoQuality, movieWidth, movieHeight );
	}
	else if ( bQLerp == true && bRLerp == false )
	{
		float D1 = GetDataRate( Q1, movieWidth, movieHeight );
		float D2 = GetDataRate( Q2, movieWidth, movieHeight );
		
		DR = D1 + Qlerp * ( D2 - D1 );
	}
	else if ( bQLerp == false && bRLerp == true )
	{
		float D1 = GetDataRate( videoQuality, RES1.X, RES1.Y );
		float D2 = GetDataRate( videoQuality, RES2.X, RES2.Y );
		
		DR = D1 + RLerp * ( D2 - D1 );
	
	}
	else  // need the full filter
	{
		float D1 = GetDataRate( Q1, RES1.X, RES1.Y );
		float D2 = GetDataRate( Q1, RES2.X, RES2.Y );
		float D3 = GetDataRate( Q2, RES1.X, RES1.Y );
		float D4 = GetDataRate( Q2, RES2.X, RES2.Y );
	
		float I1 = D1 + Qlerp * ( D3 - D1 );
		float I2 = D2 + Qlerp * ( D4 - D2 );
		
		DR = I1 + RLerp * ( I2 - I1 );
	}

	// Now do the big computation
	// should this be 1024 * 1024?

	double  VideoData = DR * 1000000 / 8 * movieDuration ;

	// Quick hack to guess at audio data size	
	double audioData = 0;
	
	if ( srcAudioFormat == AudioEncodeSourceFormat::AUDIO_16BIT_PCMStereo )
	{
		audioData = ( audioSampleRate * 2 ) * ( 0.05 * DR );
	}
	
	*pEstSize = (size_t) VideoData + (size_t) audioData;

	SetResult( VideoResult::SUCCESS );
	return true;
}


float CQuickTimeVideoRecorder::GetDataRate( int quality, int width, int height )
{
	for (int i = 0; i < ARRAYSIZE( s_H264EncodeRates ); i++ )
	{
		if ( s_H264EncodeRates[i].m_QualitySetting == quality && s_H264EncodeRates[i].m_XResolution == width && s_H264EncodeRates[i].m_YResolution == height )
		{
			return s_H264EncodeRates[i].m_DataRate;
		}
	}

	Assert( false );	
	return 0.0f;	
}





// ------------------------------------------------------------------------
// CQTVideoFileComposer - Class to encapsulate the creation of a QuickTime
//   Movie from a sequence of uncompressed images and (future) audio samples
// ------------------------------------------------------------------------
CQTVideoFileComposer::CQTVideoFileComposer() :
	m_LastResult( VideoResult::SUCCESS ),

	m_bMovieCreated( false ),
	m_bHasAudioTrack( false ),
	
	m_bMovieConfigured( false ),
	m_bSourceImagesConfigured( false ),
	m_bSourceAudioConfigured( false ),
	
	m_bComposingMovie( false ),
	m_bMovieCompleted( false ),
	
	m_nFramesAdded( 0 ),
	m_nAudioFramesAdded( 0 ),
	m_nSamplesAdded( 0 ),
	m_nSamplesAddedToMedia( 0 ),
	
	m_MovieFrameWidth( 0 ),
	m_MovieFrameHeight( 0 ),
	
	m_MovieTimeScale( 0 ),
	m_DurationPerFrame( 0 ),
	
	m_AudioOptions( AudioEncodeOptions::NO_AUDIO_OPTIONS ),
	m_SampleGrouping( AG_NONE ),
	m_nAudioSampleGroupSize( 0 ),
	
	m_AudioSourceFrequency( 0 ),
	m_AudioBytesPerSample( 0 ),
	
	m_bBufferSourceAudio( false ),
	m_bLimitAudioDurationToVideo( false ),
	
	m_srcAudioBuffer( nullptr ),
	m_srcAudioBufferSize( 0 ),
	m_srcAudioBufferCurrentSize( 0 ),
	
	m_AudioSampleFrameCounter( 0 ),
	
	m_FileName( nullptr ),
	
	m_SrcImageWidth( 0 ),
	m_SrcImageHeight( 0 ),
	m_ScrImageMaxCompressedSize( 0 ),
	m_SrcImageBuffer( nullptr ),
	m_SrcImageCompressedBuffer( nullptr ),
	m_SrcPixelFormat( 0 ),
	m_SrcBytesPerPixel( 0 ),
	
	m_GWorldPixelFormat( 0 ),
	m_GWorldBytesPerPixel( 0 ),
	m_GWorldImageWidth( 0 ),
	m_GWorldImageHeight( 0 ),
	
	m_srcSoundDescription( nullptr ),
	
	m_EncodeQuality( CQTVideoFileComposer::DEFAULT_ENCODE_QUALITY ),
	m_VideoCodecToUse( CQTVideoFileComposer::DEFAULT_CODEC ),
	m_EncodeGamma( CQTVideoFileComposer::DEFAULT_GAMMA ),
	
	m_theSrcGWorld( nullptr ),

	m_MovieFileDataRef( nullptr ),
	m_MovieFileDataRefType( 0 ),
	m_MovieFileDataHandler( nullptr ),

	m_theMovie( nullptr ),
	m_theVideoTrack( nullptr),
	m_theAudioTrack( nullptr ),
	m_theVideoMedia( nullptr ),
	m_theAudioMedia( nullptr )
	
#ifdef LOG_ENCODER_OPERATIONS
	,m_LogFile( FILESYSTEM_INVALID_HANDLE )
#endif	
{
	m_MovieRecordFPS.SetFPS( 0, false );
	m_GWorldRect.top = m_GWorldRect.left = m_GWorldRect.bottom = m_GWorldRect.right = 0;
	
#ifdef LOG_FRAMES_TO_TGA
	ZeroVar( m_TGAFileBase );
#endif		
	
}


CQTVideoFileComposer::~CQTVideoFileComposer()
{
	if ( m_bComposingMovie )
	{
		AbortMovie();
	}

#ifdef LOG_ENCODER_OPERATIONS
	if ( m_LogFile != FILESYSTEM_INVALID_HANDLE )
	{
		g_pFullFileSystem->Close( m_LogFile );
		m_LogFile = FILESYSTEM_INVALID_HANDLE;
	}

#endif


	SAFE_DELETE_ARRAY( m_FileName );
	SAFE_DELETE_ARRAY( m_SrcImageBuffer );
	SAFE_DELETE_ARRAY( m_srcAudioBuffer );

	SAFE_DISPOSE_HANDLE( m_MovieFileDataRef );
	SAFE_DISPOSE_HANDLE( m_srcSoundDescription );
	SAFE_DISPOSE_HANDLE( m_SrcImageCompressedBuffer );
	SAFE_DISPOSE_GWORLD( m_theSrcGWorld );
	
}


#ifdef LOG_ENCODER_OPERATIONS
void CQTVideoFileComposer::LogMsg( const char* pMsg, ... )
{
	const int MAX_TEXT = 8192;
	static char messageBuf[MAX_TEXT];

	if ( m_LogFile == FILESYSTEM_INVALID_HANDLE || pMsg == nullptr )
	{
		return;
	}

	va_list marker;

	va_start( marker, pMsg );

#ifdef _WIN32
	int len = _vsnprintf( messageBuf, MAX_TEXT, pMsg, marker );
#elif POSIX
	int len = vsnprintf( messageBuf, MAX_TEXT, pMsg, marker );
#else
	#error "define vsnprintf type."
#endif

	// Len < 0 represents an overflow
	if( len < 0 )
	{
		((char*) pMsg)[MAX_TEXT-1] = nullchar;
	}
	va_end( marker );

	g_pFullFileSystem->Write( messageBuf, V_strlen( messageBuf ), m_LogFile );

}
#endif 


bool CQTVideoFileComposer::CreateNewMovie( const char *fileName, bool hasAudio )
{
	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_NOT_EMPTY( fileName ) );
	
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( !m_bMovieCreated && !m_bMovieCompleted );

#ifdef LOG_ENCODER_OPERATIONS
	char logFileName[MAX_PATH];
	V_strncpy( logFileName, fileName, MAX_PATH );
	V_SetExtension( logFileName, ".log", MAX_PATH );
	m_LogFile = g_pFullFileSystem->Open( logFileName, "wb" );
	const char* aMsg = (hasAudio) ? "HAS" : "DOES NOT HAVE";
	LogMsg( "Creating Video File: '%s'  - %s AUDIO TRACK\n", fileName, aMsg );
#endif

	// now create the movie file

	OSErr	status = noErr;
	OSType movieType = FOUR_CHAR_CODE('TVOD');			// todo - change movie type??

	m_MovieFileDataRef = nullptr;
	m_MovieFileDataRefType = 0;
	m_MovieFileDataHandler = nullptr;
	
	CFStringRef	imageStrRef = CFStringCreateWithCString ( NULL,  fileName, 0 ); 
	
	status = QTNewDataReferenceFromFullPathCFString( imageStrRef, (QTPathStyle) kQTNativeDefaultPathStyle, 0, &m_MovieFileDataRef, &m_MovieFileDataRefType );
	AssertExitF( status == noErr );
	
	
	status = CreateMovieStorage( m_MovieFileDataRef, m_MovieFileDataRefType, movieType, smCurrentScript,  createMovieFileDeleteCurFile | createMovieFileDontCreateResFile, &m_MovieFileDataHandler, &m_theMovie );
	AssertExitF( status == noErr );

	CFRelease( imageStrRef );
    m_FileName = COPY_STRING( fileName );

#ifdef LOG_FRAMES_TO_TGA
	V_strncpy( m_TGAFileBase, m_FileName, sizeof( m_TGAFileBase ) );
	V_StripExtension( m_TGAFileBase, m_TGAFileBase, sizeof( m_TGAFileBase ) );
#endif

	// we did it! party on...	
	SetResult( VideoResult::SUCCESS );
	m_bMovieCreated = true;
	m_bHasAudioTrack = hasAudio;

	return m_bMovieCreated;
}


bool CQTVideoFileComposer::SetMovieVideoParameters( int width, int height, VideoFrameRate_t movieFPS, VideoEncodeCodec_t desiredCodec, int encodeQuality, VideoEncodeGamma_t gamma )
{
	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGE( width, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( height, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
	AssertExitF( IS_IN_RANGE( movieFPS.GetFPS(), cMinFPS, cMaxFPS ) );
	AssertExitF( IS_IN_RANGECOUNT( desiredCodec, VideoEncodeCodec::DEFAULT_CODEC, VideoEncodeCodec::CODEC_COUNT ) );
	AssertExitF( IS_IN_RANGE( encodeQuality, VideoEncodeQuality::MIN_QUALITY, VideoEncodeQuality::MAX_QUALITY ) );
	AssertExitF( IS_IN_RANGECOUNT( gamma, VideoEncodeGamma::NO_GAMMA_ADJUST, VideoEncodeGamma::GAMMA_COUNT ) );
	
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bMovieCreated && !m_bMovieConfigured );

	// Configure video parameters
	m_MovieFrameWidth = width;
	m_MovieFrameHeight = height;

	// map the requested codec in 
	switch( desiredCodec )
	{
		case VideoEncodeCodec::MPEG2_CODEC:
		{
			m_VideoCodecToUse = kMpegYUV420CodecType;
			break;
		}
		case VideoEncodeCodec::MPEG4_CODEC:
		{
			m_VideoCodecToUse = kMPEG4VisualCodecType;
			break;
		}
		case VideoEncodeCodec::H261_CODEC:
		{
			m_VideoCodecToUse = kH261CodecType;
			break;
		}
		case VideoEncodeCodec::H263_CODEC:
		{
			m_VideoCodecToUse = kH263CodecType;
			break;
		}
		case VideoEncodeCodec::H264_CODEC:
		{
			m_VideoCodecToUse = kH264CodecType;
			break;
		}
		case VideoEncodeCodec::MJPEG_A_CODEC:
		{
			m_VideoCodecToUse = kMotionJPEGACodecType;
			break;
		}
		case VideoEncodeCodec::MJPEG_B_CODEC:
		{
			m_VideoCodecToUse = kMotionJPEGBCodecType;
			break;
		}
		case VideoEncodeCodec::SORENSON3_CODEC:
		{
			m_VideoCodecToUse = kSorenson3CodecType;
			break;
		}
		case VideoEncodeCodec::CINEPACK_CODEC:
		{
			m_VideoCodecToUse = kCinepakCodecType;
			break;
		}
		default:										// should never hit this because we are already range checked
		{
			m_VideoCodecToUse = CQTVideoFileComposer::DEFAULT_CODEC;
			break;
		}
	}

	// Determine if codec is available...
	CodecInfo	theInfo;
	
	OSErr status = GetCodecInfo( &theInfo, m_VideoCodecToUse, 0 );
	if ( status == noCodecErr )
	{
		SetResult( VideoResult::CODEC_NOT_AVAILABLE );
		return false;
	}
	AssertExitF( status == noErr );

#ifdef LOG_ENCODER_OPERATIONS
	char codecName[64];
	ZeroVar( codecName );
	V_memcpy( codecName, &theInfo.typeName[1], (int) theInfo.typeName[0] );

	LogMsg( "Video Image Size is (%d x %d)\n", m_MovieFrameWidth, m_MovieFrameHeight );
	LogMsg( "Codec selected is %s\n", codecName );
	LogMsg( "Encoding Quality = %d\n", (int) encodeQuality );
	LogMsg( "Encode Gamma = %d\n", (int) gamma );
#endif

	// convert encoding quality into quicktime specific value
	int Q = (int) encodeQuality; - (int) VideoEncodeQuality::MIN_QUALITY;
	int MaxQ = (int) VideoEncodeQuality::MAX_QUALITY - (int) VideoEncodeQuality::MIN_QUALITY;
	
	m_EncodeQuality = codecLosslessQuality * ( (float) Q  / (float) MaxQ ) ;
	clamp( m_EncodeQuality, codecMinQuality, codecMaxQuality );

	// convert the gamma correction value into quicktime specific values
	switch( gamma )
	{
		case VideoEncodeGamma::NO_GAMMA_ADJUST:
		{
			m_EncodeGamma = kQTUseSourceGammaLevel;
			break;
		}
		case VideoEncodeGamma::PLATFORM_STANDARD_GAMMA:
		{
			m_EncodeGamma = kQTUsePlatformDefaultGammaLevel;
			break;
		}
		case VideoEncodeGamma::GAMMA_1_8:
		{
			m_EncodeGamma = 0x0001CCCC;		// (Fixed) Gamma 1.8
			break;
		}
		case VideoEncodeGamma::GAMMA_2_2:
		{
			m_EncodeGamma = kQTCCIR601VideoGammaLevel;
			break;
		}
		case VideoEncodeGamma::GAMMA_2_5:
		{
			m_EncodeGamma = 0x00028000;		// (Fixed) Gamma 2.5
			break;
		}
		default:
		{
			m_EncodeGamma = CQTVideoFileComposer::DEFAULT_GAMMA;
			break;
		}
	}
	
	// Process the framerate into usable values

	m_MovieRecordFPS = movieFPS;
	
	m_DurationPerFrame = m_MovieRecordFPS.GetUnitsPerFrame();
	m_MovieTimeScale   = m_MovieRecordFPS.GetUnitsPerSecond();
	
	AssertExitF( m_DurationPerFrame > 0 && m_MovieTimeScale > 0 );
	
/*	if ( movieFPS.IsNTSCRate() )
	{
		m_MovieTimeScale	= movieFPS.GetIntFPS() * 1000;
		m_DurationPerFrame	= 1001;
	}
	else if ( movieFPS.GetUnitsPerSecond() % movieFPS.GetUnitsPerFrame() == 0 )		// integer frame rate?
	{
		m_MovieTimeScale	= movieFPS.GetIntFPS() * 1000;
		m_DurationPerFrame  = 1000;
	}
	else	// round to nearest .001 second
	{
		m_MovieTimeScale  = (int) ( movieFPS.GetFPS() * 1000 );
		m_DurationPerFrame  = 1000;
	}
*/

#ifdef LOG_ENCODER_OPERATIONS
	LogMsg( "Video Frame Rate = %f FPS\n   %d time units per second\n   %d time units per frame\n", m_MovieRecordFPS.GetFPS(), m_MovieRecordFPS.GetUnitsPerSecond(), m_MovieRecordFPS.GetUnitsPerFrame() );
	if ( m_MovieRecordFPS.IsNTSCRate() )
		LogMsg( "   IS CONSIDERED NTSC RATE\n");
	LogMsg( "MovieTimeScale is being set to  %d\nDuration Per Frame is  %d\n\n", m_MovieTimeScale, m_DurationPerFrame );
#endif

	// Create the video track and media
	SetResult( VideoResult::VIDEO_ERROR_OCCURED );

	m_theVideoTrack = NewMovieTrack( m_theMovie, FixRatio( width, 1 ), FixRatio( height, 1 ), kNoVolume );
	AssertExitF( GetMoviesError() == noErr );
	
	m_theVideoMedia = NewTrackMedia( m_theVideoTrack, VideoMediaType, m_MovieTimeScale, NULL, 0 );
	AssertExitF( GetMoviesError() == noErr );

	// we have successfully configured the output movie
	SetResult( VideoResult::SUCCESS );
	m_bMovieConfigured = true;
	
	return true;
}


bool CQTVideoFileComposer::SetMovieSourceImageParameters( int srcWidth, int srcHeight, VideoEncodeSourceFormat_t srcImageFormat )
{
	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGE( srcWidth, cMinVideoFrameWidth, cMaxVideoFrameWidth ) && IS_IN_RANGE( srcHeight, cMinVideoFrameHeight, cMaxVideoFrameHeight ) );
	AssertExitF( IS_IN_RANGECOUNT( srcImageFormat, VideoEncodeSourceFormat::VIDEO_FORMAT_FIRST, VideoEncodeSourceFormat::VIDEO_FORMAT_COUNT ) );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bMovieCreated && !m_bMovieCompleted && m_bMovieConfigured && !m_bSourceImagesConfigured );

	// Setup source image format related stuff
	m_SrcPixelFormat = ( srcImageFormat == VideoEncodeSourceFormat::BGRA_32BIT ) ? k32BGRAPixelFormat :
					   ( srcImageFormat == VideoEncodeSourceFormat::BGR_24BIT  ) ? k24BGRPixelFormat :
					   ( srcImageFormat == VideoEncodeSourceFormat::RGB_24BIT ) ? k24RGBPixelFormat :
					   ( srcImageFormat == VideoEncodeSourceFormat::RGBA_32BIT ) ? k32RGBAPixelFormat : 0;

	m_SrcBytesPerPixel = GetBytesPerPixel( m_SrcPixelFormat );
	
	// Setup source image size related stuff
	m_SrcImageWidth = srcWidth;
	m_SrcImageHeight = srcHeight;
	m_SrcImageSize = srcWidth * srcHeight * m_SrcBytesPerPixel;

	// Setup the GWorld to hold the frame to video compress	

	m_GWorldPixelFormat = k32BGRAPixelFormat;			// can use k24BGRPixelFormat on Win32.. but it compresses wrong on OSX?
	m_GWorldBytesPerPixel = 4;
	m_GWorldImageWidth  = CONTAINING_MULTIPLE_OF( srcWidth, 4 );			// make sure the encoded surface is a multiple of 4 in each dimensions
	m_GWorldImageHeight = CONTAINING_MULTIPLE_OF( srcHeight, 4 );
	
	m_GWorldRect.top = m_GWorldRect.left = 0;
	m_GWorldRect.bottom = m_GWorldImageHeight;
	m_GWorldRect.right = m_GWorldImageWidth;
	
	// Setup the QuiuckTime Graphics World for incoming frames of video
	// Always use a 32-bit GWORD to avoid encoding bugs
	SetResult( VideoResult::VIDEO_ERROR_OCCURED );
	
	OSErr status = QTNewGWorld( &m_theSrcGWorld, m_GWorldPixelFormat, &m_GWorldRect, nil, nil, 0 );
	AssertExitF( status == noErr );

	PixMapHandle  thePixMap = GetGWorldPixMap( m_theSrcGWorld );
	AssertPtrExitF( thePixMap );

	status = QTSetPixMapHandleRequestedGammaLevel( thePixMap, m_EncodeGamma );
	AssertExitF( status == noErr );

	// Set encoding buffer to max size at max quality
	// Should we try it with the actual quality setting?
	
	status = GetMaxCompressionSize(	thePixMap, &m_GWorldRect, 0, m_EncodeQuality, m_VideoCodecToUse, 
									(CompressorComponent)anyCodec, (long*) &m_ScrImageMaxCompressedSize );
									
	AssertExitF( status == noErr && m_ScrImageMaxCompressedSize > 0 );

	// allocated buffers for the uncompressed and compressed images
	m_SrcImageBuffer = new byte[ m_SrcImageSize ];
	m_SrcImageCompressedBuffer = NewHandle( m_ScrImageMaxCompressedSize );

	// we have successfully configured the video input images
	SetResult( VideoResult::SUCCESS );
	m_bSourceImagesConfigured = true;
	
	return CheckForReadyness();		// We are ready to go if audio is...
}


bool CQTVideoFileComposer::SetMovieSourceAudioParameters( AudioEncodeSourceFormat_t srcAudioFormat, int audioSampleRate, AudioEncodeOptions_t audioOptions, int audioSampleGroupSize )
{
	SetResult( VideoResult::ILLEGAL_OPERATION );
	AssertExitF( m_bHasAudioTrack );

	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( IS_IN_RANGECOUNT( srcAudioFormat, AudioEncodeSourceFormat::AUDIO_NONE, AudioEncodeSourceFormat::AUDIO_FORMAT_COUNT ) );
	AssertExitF( audioSampleRate == 0 || IS_IN_RANGE( audioSampleRate, cMinSampleRate, cMaxSampleRate ) );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bMovieCreated && !m_bMovieCompleted && m_bMovieConfigured && !m_bSourceAudioConfigured );

	// it is possible to disable audio here by passing in AudioEncodeSourceFormat::AUDIO_NONE even
	// if the movie was created with the hasHadio flag set to true, or by setting the sample rate to 0
	
	if ( srcAudioFormat == AudioEncodeSourceFormat::AUDIO_NONE || audioSampleRate == 0 )
	{
		m_bHasAudioTrack = false;
	}
	else
	{
		m_AudioOptions = audioOptions;
	
		// Setup the audio frequency
		m_AudioSourceFrequency = audioSampleRate;

		// Create the audio track and media
		SetResult( VideoResult::AUDIO_ERROR_OCCURED );

		m_theAudioTrack = NewMovieTrack( m_theMovie, 0, 0, kFullVolume );
		AssertExitF( GetMoviesError() == noErr );
		
		m_theAudioMedia = NewTrackMedia( m_theAudioTrack, SoundMediaType, (TimeScale) audioSampleRate, NULL, 0 );
		AssertExitF( GetMoviesError() == noErr );

		// Setup the Audio Sound description
		AudioStreamBasicDescription  inASBD;
		
		switch( srcAudioFormat )
		{
			case AudioEncodeSourceFormat::AUDIO_16BIT_PCMStereo:
			{
				inASBD.mSampleRate			= Float64( audioSampleRate );
				inASBD.mFormatID			= kAudioFormatLinearPCM;
				inASBD.mFormatFlags			= kAudioFormatFlagIsSignedInteger | kAudioFormatFlagIsPacked;
				inASBD.mBytesPerPacket		= 4;
				inASBD.mFramesPerPacket		= 1;
				inASBD.mBytesPerPacket		= 4;
				inASBD.mChannelsPerFrame	= 2;
				inASBD.mBitsPerChannel		= 16;
				inASBD.mReserved			= 0;
				break;
			}
			default:
			{
				Assert( false );			// Impossible.. we hope
				return false;
			}
		}

		m_AudioBytesPerSample = inASBD.mBytesPerPacket;
	
		OSStatus result = QTSoundDescriptionCreate( &inASBD, NULL, 0, NULL, 0, kQTSoundDescriptionKind_Movie_LowestPossibleVersion, (SoundDescriptionHandle*) &m_srcSoundDescription );
		AssertExitF( result == noErr );

		// Setup audio sample buffering if needed
		
		m_bLimitAudioDurationToVideo = BITFLAGS_SET( audioOptions, AudioEncodeOptions::LIMIT_AUDIO_TRACK_TO_VIDEO_DURATION );
		
		m_SampleGrouping = ( BITFLAGS_SET( audioOptions, AudioEncodeOptions::GROUP_SIZE_IS_VIDEO_FRAME ) ) ? CQTVideoFileComposer::AG_PER_FRAME : 
						   ( BITFLAGS_SET( audioOptions, AudioEncodeOptions::USE_AUDIO_ENCODE_GROUP_SIZE ) ) ? CQTVideoFileComposer::AG_FIXED_SIZE : AG_NONE;
		
		// check for invalid sample grouping duration
		if ( m_SampleGrouping ==  AG_FIXED_SIZE && ( audioSampleGroupSize < MIN_AUDIO_SAMPLE_GROUP_SIZE || audioSampleGroupSize > MAX_AUDIO_GROUP_SIZE_IN_SEC * m_AudioSourceFrequency ) ) 
		{
			SetResult( VideoResult::BAD_INPUT_PARAMETERS );
			Assert( false );
			return false;	
		}
		
		m_bBufferSourceAudio = ( m_SampleGrouping != AG_NONE ) || m_bLimitAudioDurationToVideo;

		// Set up an audio buffer than can hold the maxium specified duration
		if ( m_bBufferSourceAudio )
		{
			m_srcAudioBufferSize = m_AudioSourceFrequency * m_AudioBytesPerSample * MAX_AUDIO_GROUP_SIZE_IN_SEC;
			m_srcAudioBuffer = new byte[m_srcAudioBufferSize];
			m_srcAudioBufferCurrentSize = 0;
		}

		if ( m_SampleGrouping == AG_FIXED_SIZE )		
		{
			// Set up to emit audio after fixed number of samples
			m_nAudioSampleGroupSize = audioSampleGroupSize;
			
		}

		if ( m_SampleGrouping == AG_PER_FRAME )
		{
			m_AudioSampleFrameCounter = 0;
		}
	
		m_bSourceAudioConfigured = true;
	}

#ifdef LOG_ENCODER_AUDIO_OPERATIONS
	LogMsg( "Audio Sample Grouping Mode = %d\nSample Group Size = %d \n", (int) m_SampleGrouping, m_nAudioSampleGroupSize );
	LogMsg( "Audio Track Sample Rate is %d samples per second\n", m_AudioSourceFrequency );
	LogMsg( "Estimated Samples per frame = %d\n\n",  (int) ( m_AudioSourceFrequency / m_MovieRecordFPS.GetFPS() ) );
#endif

	// finish up
	SetResult( VideoResult::SUCCESS );
	
	return CheckForReadyness();				// We are ready to go if video is...
}


// Returns true if we are not ready, or if we began movie creation successfully
// This ONLY returns false if it tried to begin the movie creation process and failed
bool CQTVideoFileComposer::CheckForReadyness()
{
	return ( m_bMovieCreated && !m_bMovieCompleted && !m_bComposingMovie &&  m_bMovieConfigured && m_bSourceImagesConfigured && 
	         m_bSourceAudioConfigured == m_bHasAudioTrack ) ? BeginMovieCreation() : true;
}


bool CQTVideoFileComposer::BeginMovieCreation()
{
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bMovieCreated && !m_bMovieCompleted && !m_bComposingMovie && 
	             m_bMovieConfigured && m_bSourceImagesConfigured && m_bSourceAudioConfigured == m_bHasAudioTrack );

	// Open the tracks up for editing
	SetResult( VideoResult::VIDEO_ERROR_OCCURED );
	OSErr status = BeginMediaEdits( m_theVideoMedia );
	AssertExitF( status == noErr );

	if ( m_bHasAudioTrack )
	{
		OSErr status = BeginMediaEdits( m_theAudioMedia );
		AssertExitF( status == noErr );
	}


#ifdef LOG_ENCODER_OPERATIONS
	LogMsg( "Media Tracks opened for editing\n\n" );
#endif


	// We are now ready to take in data to make a movie with
	SetResult( VideoResult::SUCCESS );
	m_bComposingMovie = true;
	
	return true;
}


bool CQTVideoFileComposer::AppendVideoFrameToMedia( void *ImageBuffer, int strideAdjustBytes )
{
#ifdef LOG_ENCODER_OPERATIONS
	LogMsg( "AppendVideoFrameToMedia( %8.8x ) called for %d --- ", ImageBuffer, m_nFramesAdded+1 );
#endif

	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( ImageBuffer != nullptr );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bComposingMovie && !m_bMovieCompleted );

	SetResult( VideoResult::VIDEO_ERROR_OCCURED );

	// Get the pixmap
	PixMapHandle  thePixMap = GetGWorldPixMap( m_theSrcGWorld );
	AssertPtrExitF( thePixMap );

	// copy the raw image into our bitmap
	AssertExitF( LockPixels( thePixMap ) );

	byte *srcBase = (byte*) ImageBuffer;
	int  srcStride = m_SrcImageWidth * m_SrcBytesPerPixel + strideAdjustBytes;
	
	byte *dstBase = nullptr;
	int  dstStride = 0;	

#if defined ( WIN32 )
	// Get the HBITMAP of our GWorld
	HBITMAP theHBITMAP = (HBITMAP) GetPortHBITMAP( (GrafPtr) m_theSrcGWorld );

	// retrieve the bitmap info header information
	BITMAP bmp; 
	AssertExitF( GetObject( theHBITMAP, sizeof(BITMAP), (LPSTR) &bmp) );

	// validate the BMP we just got
	AssertExitF( bmp.bmWidth == m_SrcImageWidth && bmp.bmHeight == m_SrcImageHeight && bmp.bmBitsPixel == 8 * m_GWorldBytesPerPixel );

	// setup the pixel copy info
	dstBase = (byte*)bmp.bmBits;
	dstStride = bmp.bmWidthBytes;

#elif defined ( OSX )	
	// setup the pixel copy info
	dstBase = (byte*) GetPixBaseAddr( thePixMap );
	dstStride = GetPixRowBytes( thePixMap );	

#endif

	AssertExitF( dstBase != nullptr && dstStride > 0 );

	// save a TGA if we are running diagnostics
#if defined ( LOG_FRAMES_TO_TGA )

	if ( ( m_nFramesAdded % LOG_FRAMES_TO_TGA_INTERVAL ) == 0 ) 
	{
		SaveToTargaFile( m_nFramesAdded, m_TGAFileBase, m_SrcImageWidth, m_SrcImageHeight, srcBase, m_SrcPixelFormat, strideAdjustBytes );
	}

#endif 

	// copy the supplied pixel buffer into our GWORLD data
	if ( !CopyBitMapPixels( m_SrcImageWidth, m_SrcImageHeight, 
							m_SrcPixelFormat, srcBase, srcStride, 
	                        m_GWorldPixelFormat, dstBase, dstStride ) )
	{
		Assert( false );
		return false;
	}

	// You are now free to move about the cabin...
	UnlockPixels( thePixMap );

	// allocate a handle which CompressImage will resize...
	ImageDescriptionHandle theImageDescHandle = (ImageDescriptionHandle) NewHandle( sizeof(ImageDescriptionHandle) );
	AssertExitF( theImageDescHandle != nullptr );

	// compress the single image
	OSErr status = CompressImage( thePixMap, &m_GWorldRect, m_EncodeQuality,
		   	   					  m_VideoCodecToUse, theImageDescHandle, *m_SrcImageCompressedBuffer );
	if ( status != noErr )
	{
		Assert( false );		// tell the user
		SAFE_DISPOSE_HANDLE( theImageDescHandle );
		return false;
	}

 	TimeValue	addedTime = 0;

	// Lets add gamma info the image description 	
	if ( m_EncodeGamma != kQTUseSourceGammaLevel )
	{
	 	Fixed newGamma = m_EncodeGamma;
	 	status = ICMImageDescriptionSetProperty( theImageDescHandle, kQTPropertyClass_ImageDescription, kICMImageDescriptionPropertyID_GammaLevel, sizeof( newGamma ), &newGamma );
		AssertExitF( status == noErr );
	}
	
	// add the compressed image to the movie stream
	status = AddMediaSample( m_theVideoMedia, m_SrcImageCompressedBuffer, 0, (**theImageDescHandle).dataSize, m_DurationPerFrame,	
							(SampleDescriptionHandle) theImageDescHandle, 1, 0, &addedTime );
								
	if ( status != noErr )
	{
		Assert( false );		// tell the user
		SAFE_DISPOSE_HANDLE( theImageDescHandle );
		return false;
	}


#ifdef LOG_ENCODER_OPERATIONS
	LogMsg( "Video Frame %d added to Video Media: Duration = %d, Inserted at Time %d\n", m_nFramesAdded+1, m_DurationPerFrame, addedTime );
#endif

	// free up dynamic resources
	SAFE_DISPOSE_HANDLE( theImageDescHandle );

	// Report success
	SetResult( VideoResult::SUCCESS );
	m_nFramesAdded++;
	
	return true;
}



int CQTVideoFileComposer::GetAudioSampleCountThruFrame( int frameNo )
{
	if ( frameNo < 1 )
	{
		return 0;
	}

	double  secondsSoFar  = (double) ( frameNo * m_DurationPerFrame ) / (double) m_MovieTimeScale;
	int		nAudioSamples = (int) floor( secondsSoFar * (double) m_AudioSourceFrequency );
	
	return nAudioSamples;
}



bool CQTVideoFileComposer::AppendAudioSamplesToMedia( void *soundBuffer, size_t bufferSize )
{
	SetResult( VideoResult::ILLEGAL_OPERATION );
	AssertExitF( m_bHasAudioTrack );

	// Validate input and state
	SetResult( VideoResult::BAD_INPUT_PARAMETERS );
	AssertExitF( soundBuffer != nullptr && bufferSize % m_AudioBytesPerSample == 0 );

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bComposingMovie && !m_bMovieCompleted );

	int nSamples = bufferSize / m_AudioBytesPerSample;	
	Assert( bufferSize % m_AudioBytesPerSample == 0 );

	TimeValue64		insertTime64 = 0;
	OSErr			status = noErr;

	bool	retest;
	int		samplesToEmit, MaxCanAdd, nSamplesAvailable;

	m_nSamplesAdded+= nSamples;									// track samples given to encoder

	#ifdef LOG_ENCODER_AUDIO_OPERATIONS
		LogMsg( "%d Audio Samples Submitted (%d total) -- ", nSamples, m_nSamplesAdded );
	#endif

	// We can pass in 0 bytes to trigger a flush...
	if ( nSamples == 0 )
	{
		if ( !m_bBufferSourceAudio  || m_srcAudioBufferCurrentSize == 0 )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "NO SAMPLES TO PROCESS.  EXIT\n" );
			#endif
			goto finish_up;
		}
	}
	
	// Are we not buffering audio?
	if ( !m_bBufferSourceAudio && nSamples > 0 )
	{
		SetResult( VideoResult::AUDIO_ERROR_OCCURED );
		status = AddMediaSample2( m_theAudioMedia, (const UInt8 *) soundBuffer, (ByteCount) bufferSize,
								  (TimeValue64) 1, (TimeValue64) 0, (SampleDescriptionHandle) m_srcSoundDescription,
								  (ItemCount) nSamples, 0, &insertTime64 );             
										
		AssertExitF( status == noErr );
		
		m_nSamplesAddedToMedia+= nSamples;
		
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "%d samples (%d total) inserted into Video at time %ld\n", nSamples, m_nSamplesAddedToMedia, insertTime64 );
		#endif
		
		goto finish_up;
	}

	// Buffering audio ....
	if ( nSamples > 0 )
	{
		memaddr_t pSrc = (memaddr_t) soundBuffer;
		size_t bytesToCopy = nSamples * m_AudioBytesPerSample;
		
		// Is buffer big enough to hold it all?
		if ( m_srcAudioBufferCurrentSize + bytesToCopy > m_srcAudioBufferSize )
		{
			// get a bigger buffer
			size_t  newBufferSize = m_srcAudioBufferSize * 2 + bytesToCopy;
			byte   *newBuffer = new byte[newBufferSize];
			
			// copy buffered sound and swap out buffers
			V_memcpy( newBuffer, m_srcAudioBuffer, m_srcAudioBufferCurrentSize );
			
			delete[] m_srcAudioBuffer;
			m_srcAudioBuffer = newBuffer;
			m_srcAudioBufferSize = newBufferSize;
		}
		
		// Append samples to buffer
		V_memcpy( m_srcAudioBuffer + m_srcAudioBufferCurrentSize, pSrc, bytesToCopy );
		m_srcAudioBufferCurrentSize += bytesToCopy;
	}
	
#ifdef LOG_ENCODER_AUDIO_OPERATIONS
	LogMsg( "%d Samples buffered.  Buffer=%d Samples  -- ", nSamples, ( m_srcAudioBufferCurrentSize / m_AudioBytesPerSample ) );
#endif

retest_here:
	nSamplesAvailable = m_srcAudioBufferCurrentSize / m_AudioBytesPerSample;
	samplesToEmit = 0;
	retest = false;
	MaxCanAdd = ( m_bLimitAudioDurationToVideo ) ? ( GetAudioSampleCountThruFrame( m_nFramesAdded ) - m_nSamplesAddedToMedia ) : INT32_MAX;

	if ( MaxCanAdd <= 0 )
	{
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "Can't Add Audio Now.\n" );
		#endif
		goto finish_up;
	}

	// Now.. we determine if we are ready to insert the audio samples into the media..and if so, how much...	
	
	if ( m_SampleGrouping == AG_NONE )
	{
		// are we keeping audio from getting ahead of video?
		Assert( m_bLimitAudioDurationToVideo );
		
		samplesToEmit = MIN( MaxCanAdd, nSamplesAvailable );
	}
	else if ( m_SampleGrouping == AG_FIXED_SIZE )
	{
		// do we have enough to emit a sample?
		if ( ( nSamplesAvailable < m_nAudioSampleGroupSize ) || ( m_bLimitAudioDurationToVideo && ( MaxCanAdd < m_nAudioSampleGroupSize ) ) )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				if ( nSamplesAvailable < m_nAudioSampleGroupSize ) 
					LogMsg( "Need %d Samples to emit sample group\n", m_nAudioSampleGroupSize );
				else
					LogMsg( "Audio is caught up to Video (can add %d) \n", MaxCanAdd );
			#endif
			goto finish_up;			
		}
		
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "emitting 1 group of audio (%d samples)\n", m_nAudioSampleGroupSize );
		#endif		
		
		samplesToEmit = m_nAudioSampleGroupSize;
		retest = true;
	}
	else if ( m_SampleGrouping == AG_PER_FRAME )
	{
		// is the audio already caught up with the current video frame?
		if ( m_bLimitAudioDurationToVideo && m_AudioSampleFrameCounter >= m_nFramesAdded )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Audio is caught up to Video\n" );
			#endif		
			goto finish_up;
		}
	
		int curSampleCount = GetAudioSampleCountThruFrame( m_AudioSampleFrameCounter );
		int nextSampleCount = GetAudioSampleCountThruFrame( m_AudioSampleFrameCounter+1 );
		int thisGroupSize = nextSampleCount - curSampleCount;
		
		Assert( m_nSamplesAddedToMedia == curSampleCount );

		if ( nSamplesAvailable < thisGroupSize )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Not enough samples to fill video frame (need %d)\n", thisGroupSize );
			#endif		
			goto finish_up;
		}

		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "emitting 1 video frame of audio (%d samples)\n", thisGroupSize );
		#endif		
		
		samplesToEmit = thisGroupSize;
		m_AudioSampleFrameCounter++;
		retest = true;
	}
	else
	{
		Assert( false );
	}
	
	if ( samplesToEmit > 0 )	
	{
		SetResult( VideoResult::AUDIO_ERROR_OCCURED );
	
		status = AddMediaSample2( m_theAudioMedia, (const UInt8 *) m_srcAudioBuffer, (ByteCount) samplesToEmit * m_AudioBytesPerSample,
								  (TimeValue64) 1, (TimeValue64) 0, (SampleDescriptionHandle) m_srcSoundDescription,
								  (ItemCount) samplesToEmit, 0, &insertTime64 );             
										
		AssertExitF( status == noErr );
		
		m_nSamplesAddedToMedia+= samplesToEmit;
		
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "%d samples inserted into Video (%d total) at time %ld  -- ", samplesToEmit, m_nSamplesAddedToMedia, insertTime64 );
		#endif

		// remove added samples from sound buffer
		// (this really should be a circular buffer.. but that has its own problems)		
		
		m_srcAudioBufferCurrentSize -= samplesToEmit * m_AudioBytesPerSample;
		nSamplesAvailable -= samplesToEmit;
		
		if ( nSamplesAvailable > 0 )
		{
			V_memcpy( m_srcAudioBuffer, m_srcAudioBuffer + (samplesToEmit * m_AudioBytesPerSample), nSamplesAvailable * m_AudioBytesPerSample );
		}
		
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "Buffer now =%d samples", nSamplesAvailable );
		#endif
		
		if ( retest )	
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( " -- rechecking -- "  );
			#endif
			goto retest_here;
		}
	}
	#ifdef LOG_ENCODER_AUDIO_OPERATIONS
		LogMsg( "\n" );
	#endif


finish_up:	
	// Report success
	SetResult( VideoResult::SUCCESS );
	
	return true;
}



bool CQTVideoFileComposer::SyncAndFlushAudio()
{
	if ( !m_bHasAudioTrack )
	{
		return false;
	}

	#ifdef LOG_ENCODER_AUDIO_OPERATIONS
		LogMsg( "Resolving Audio Track...\n" );
	#endif

restart_sync:
	bool	bPadWithSilence = BITFLAGS_SET( m_AudioOptions, AudioEncodeOptions::PAD_AUDIO_WITH_SILENCE );
	int		VideoDurationInSamples = GetAudioSampleCountThruFrame( m_nFramesAdded );
	int		CurShortfall = VideoDurationInSamples - m_nSamplesAddedToMedia;
	
	int		SilenceToEmit = 0;
	bool	forceFlush = false;
	bool    forcePartialGroupFlush = false;
	int		nSamplesInBuffer = ( m_bBufferSourceAudio ) ? m_srcAudioBufferCurrentSize / m_AudioBytesPerSample : 0;
	
	#ifdef LOG_ENCODER_AUDIO_OPERATIONS
		LogMsg( "Video duration is %d frames, which is %d Audio Samples\n", m_nFramesAdded, VideoDurationInSamples );
		LogMsg( "%d Samples emitted to Audio track so far.  %d samples remain in audio buffer\n", m_nSamplesAddedToMedia, nSamplesInBuffer );
		LogMsg( "Delta to sync end of audio to end of video is %d Samples\n", CurShortfall );
		LogMsg( "Pad With Silence Mode = %d, Align End of Audio With Video Mode = %d\n", (int) bPadWithSilence, (int) m_bLimitAudioDurationToVideo );
	#endif

	// not grouping samples mode
	if ( m_SampleGrouping == AG_NONE )			
	{
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "No sample grouping Mode\n" );
		#endif
		
		Assert( m_bLimitAudioDurationToVideo == m_bBufferSourceAudio );	// if we're not limiting, we're not buffering
		
		if ( m_bLimitAudioDurationToVideo && CurShortfall > 0 && bPadWithSilence )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Padding with %d samples to match video duration", CurShortfall );
			#endif
			
			SilenceToEmit = CurShortfall;			// pad with silence
		}
		
		if ( nSamplesInBuffer > 0 || SilenceToEmit > 0 )		// force if we have something to add
		{
			forceFlush = true;
		}
	}
	
	// Fixed sized grouping (and buffering)
	if ( m_SampleGrouping == AG_FIXED_SIZE )	
	{ 
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "Fixed sample grouping mode.  Group size of %d\n", m_nAudioSampleGroupSize );
		#endif
		
		// No matter what, if we have a partially filled buffer, we add silence to it to make a complete group
		// do we have a partially full buffer? if so pad with silence to make a full group
		if ( nSamplesInBuffer > 0 && nSamplesInBuffer % m_nAudioSampleGroupSize != 0 )
		{
			SilenceToEmit = m_nAudioSampleGroupSize - ( nSamplesInBuffer % m_nAudioSampleGroupSize );
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Adding %d silence samples to complete group\n", SilenceToEmit );
			#endif
			
		}
	
		int bufferedSamples = nSamplesInBuffer + SilenceToEmit;
		int newShortFall = VideoDurationInSamples - m_nSamplesAddedToMedia - bufferedSamples;
		
		if ( bPadWithSilence && newShortFall > 0 )
		{
			SilenceToEmit += newShortFall;		// pad with silence until audio matches video duration
			forceFlush = true;
			forcePartialGroupFlush = true;
			
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Adding %d silence samples to pad to match audio to video duration\n", newShortFall );
			#endif
		}
	}
	
	if ( m_SampleGrouping == AG_PER_FRAME )
	{
		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "Video Frame duraiton Audio grouping mode\n" );
		#endif

		// Have we already enough audio to match the video
		if ( m_bLimitAudioDurationToVideo && m_AudioSampleFrameCounter >= m_nFramesAdded )
		{
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Audio is caught up to Video\n" );
			#endif		
			goto audio_complete;
		}
		
		// if we have anything in the buffer... pad it out with zeros
		if ( nSamplesInBuffer > 0 )
		{
			// get the group size for the video frame the audio is currently on
			int thisGroupSize = GetAudioSampleCountThruFrame( m_AudioSampleFrameCounter+1 ) - GetAudioSampleCountThruFrame( m_AudioSampleFrameCounter );
			Assert( m_nSamplesAddedToMedia == GetAudioSampleCountThruFrame( m_AudioSampleFrameCounter ) );

			// if we already have 1 (or more) groups in the buffer.. emit them, and restart
			if ( nSamplesInBuffer >= thisGroupSize )
			{
				char  n = nullchar;
				AppendAudioSamplesToMedia( &n, 0 );
				goto restart_sync;
			}
		
			SilenceToEmit = thisGroupSize - nSamplesInBuffer;
			forceFlush = true;
			
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Adding %d silence samples to pad current group to match video frame duration\n", SilenceToEmit );
			#endif
			
		}
			
		// with the output being aligned to a video frame, do we need to add more to pad to end of the video
		
		int bufferedSamples = nSamplesInBuffer + SilenceToEmit;
		int newShortFall = VideoDurationInSamples - m_nSamplesAddedToMedia - bufferedSamples;
		if ( bPadWithSilence && newShortFall > 0 )
		{
			SilenceToEmit += newShortFall;		// pad with silence until audio matches video duration
			forceFlush = true;
			forcePartialGroupFlush = true;
			
			#ifdef LOG_ENCODER_AUDIO_OPERATIONS
				LogMsg( "Adding %d silence samples to pad audio to match video duration", newShortFall );
			#endif
		}
	
	}
		
	#ifdef LOG_ENCODER_AUDIO_OPERATIONS
		LogMsg( "\n" );
	#endif
	
	// now we append any needed silence to the audio stream...
	if ( SilenceToEmit > 0 )
	{
		int bufferSize = SilenceToEmit * m_AudioBytesPerSample;
		byte *pSilenceBuf = new byte[ bufferSize ];
		V_memset( pSilenceBuf, nullchar, bufferSize );

		#ifdef LOG_ENCODER_AUDIO_OPERATIONS
			LogMsg( "Appending %d Silence samples\n", SilenceToEmit );
		#endif
		
		AppendAudioSamplesToMedia( pSilenceBuf, bufferSize );
	}
	else
	{
		if ( forceFlush )
		{
			char  n = nullchar;
			AppendAudioSamplesToMedia( &n, 0 );
		}
	}
		
	if ( forcePartialGroupFlush &&  m_srcAudioBufferCurrentSize >0 )
	{
		int nSamplesThisAdd	 = m_srcAudioBufferCurrentSize / m_AudioBytesPerSample;
		TimeValue64	 insertTime64 = 0;
	
		OSErr status = AddMediaSample2( m_theAudioMedia, (const UInt8 *) m_srcAudioBuffer, (ByteCount) m_srcAudioBufferCurrentSize,
									   (TimeValue64) 1, (TimeValue64) 0, (SampleDescriptionHandle) m_srcSoundDescription,
									   (ItemCount) nSamplesThisAdd, 0, &insertTime64 );             
										
		AssertExitF( status == noErr );
		
		m_srcAudioBufferCurrentSize = 0;
		m_nSamplesAddedToMedia+= nSamplesThisAdd;
		
		#ifdef LOG_ENCODER_OPERATIONS
			LogMsg( "FORCED FLUSH - Audio Samples added to media.  %d added, %d total samples, inserted at time %ld\n", nSamplesThisAdd, m_nSamplesAddedToMedia, insertTime64 );
		#endif
	}


audio_complete:

	return true;
}


bool CQTVideoFileComposer::EndMovieCreation( bool saveMovieData )
{
	#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "\nEndMovieCreation Called Composing=%d  Completed=%d\n\n", (int) m_bComposingMovie, (int) m_bMovieCompleted );
	#endif

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bComposingMovie && !m_bMovieCompleted );

	#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "\nEndMovieCreation Called\n\n" );
	#endif

	// Stop adding to and (optionally) save the video media into the file
	SetResult( VideoResult::VIDEO_ERROR_OCCURED );
	if ( m_nFramesAdded > 0 )
	{
		TimeValue VideoDuration = GetMediaDuration( m_theVideoMedia );
		AssertExitF( VideoDuration == m_nFramesAdded * m_DurationPerFrame );

		OSErr status = EndMediaEdits( m_theVideoMedia );
		AssertExitF( status == noErr );

		if ( saveMovieData )
		{
			status = InsertMediaIntoTrack( m_theVideoTrack, 0, 0, VideoDuration, fixed1 );
			Assert( status == noErr );
			
			#ifdef LOG_ENCODER_OPERATIONS
				LogMsg( "\nVideo Media inserted into Track\n" );
			#endif
			
		}
	}
	
	// Stop adding to and (optionally) save the audio media into the file
	SetResult( VideoResult::AUDIO_ERROR_OCCURED );
	if ( m_bHasAudioTrack && m_nSamplesAdded > 0 )	
	{
		// flush any remaining samples in the buffer to the media
		
	#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "Calling SyncAndFlushAudio()\n" );
	#endif
		
		SyncAndFlushAudio();
	
		TimeValue AudioDuration = GetMediaDuration( m_theAudioMedia );
		#ifdef LOG_ENCODER_OPERATIONS
			LogMsg( "Audio Duration = %d  nSamples Added = %d\n", AudioDuration, m_nSamplesAdded );
		#endif
		// AssertExitF( AudioDuration == m_nSamplesAdded );
		
		OSErr status = EndMediaEdits( m_theAudioMedia );
		AssertExitF( status == noErr );

		if ( saveMovieData )
		{
			status = InsertMediaIntoTrack( m_theAudioTrack, 0, 0, AudioDuration, fixed1 );
			AssertExitF( status == noErr );
			
			#ifdef LOG_ENCODER_OPERATIONS
				LogMsg( "\nAudio Media inserted into Track\n" );
			#endif
		}
	}

	if ( saveMovieData )
	{

#ifdef LOG_ENCODER_OPERATIONS	
		LogMsg( "Saving Movie Data...\n" );
#endif

		SetResult( VideoResult::FILE_ERROR_OCCURED );
		OSErr status = AddMovieToStorage( m_theMovie, m_MovieFileDataHandler );
		AssertExitF( status == noErr );
		if ( status != noErr )
		{
			DataHDeleteFile( m_MovieFileDataHandler );
		}
		
		#ifdef LOG_ENCODER_OPERATIONS
			LogMsg( "\nMovie Resource added to file.   Returned Status = %d\n", (int) status );
		#endif
	}

	// free our resources
	if ( m_MovieFileDataHandler != nullptr )
	{
		OSErr status = CloseMovieStorage( m_MovieFileDataHandler );
		m_MovieFileDataHandler = nullptr;
		AssertExitF( status == noErr );
	}
	
	SAFE_DISPOSE_HANDLE( m_MovieFileDataRef );
	SAFE_DISPOSE_HANDLE( m_SrcImageCompressedBuffer );
	SAFE_DISPOSE_GWORLD( m_theSrcGWorld );
	SAFE_DISPOSE_HANDLE( m_srcSoundDescription );

	SetResult( VideoResult::SUCCESS );
	m_bComposingMovie = false;	
	return true;
}


// The movie can be aborted at any time before completion
bool CQTVideoFileComposer::AbortMovie()
{
	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( !m_bMovieCompleted );

	// Shut down the movie if we are recording	
	if ( m_bComposingMovie )
	{
		if ( !EndMovieCreation( false ) )
		{
			return false;
		}
	}

	if ( m_bMovieCreated )
	{
		if (  m_MovieFileDataHandler != nullptr )
		{
			SetResult( VideoResult::FILE_ERROR_OCCURED );
			OSErr status = CloseMovieStorage( m_MovieFileDataHandler );
            AssertExitF( status == noErr );
			m_MovieFileDataHandler = nullptr;
		}
	
		SAFE_DISPOSE_HANDLE( m_MovieFileDataRef );
		SAFE_DISPOSE_MOVIE( m_theMovie );
	}

	if ( m_FileName )
	{
		g_pFullFileSystem->RemoveFile( m_FileName );
	}

	SetResult( VideoResult::SUCCESS );
	m_bMovieCompleted = true;
	
	return true;
}



bool CQTVideoFileComposer::FinishMovie( bool SaveMovieToDisk ) 
{
	#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "\nFinish Movie Called\n" );
	#endif

	SetResult( VideoResult::OPERATION_OUT_OF_SEQUENCE );
	AssertExitF( m_bComposingMovie && !m_bMovieCompleted );

	// Shutdown movie creation
	if ( !EndMovieCreation( SaveMovieToDisk )  )
	{
	#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "\nEndMovieCreation Aborted\n" );
	#endif
		return false;
	}

	// todo: check on Disposing of theMovie and theMedia
	if (  m_MovieFileDataHandler != nullptr )
	{
		SetResult( VideoResult::FILE_ERROR_OCCURED );
		OSErr status = CloseMovieStorage( m_MovieFileDataHandler );
		AssertExitF( status == noErr );
		m_MovieFileDataHandler = nullptr;
		
#ifdef LOG_ENCODER_OPERATIONS
		LogMsg( "Movie File Closed\n" );
#endif
		
	}
	
	SAFE_DISPOSE_HANDLE( m_MovieFileDataRef );
	SAFE_DISPOSE_MOVIE( m_theMovie );
	
	// if no frames have been added.. delete files
	if ( SaveMovieToDisk == false || ( m_nFramesAdded <= 0 && m_nSamplesAdded <= 0) )
	{
		g_pFullFileSystem->RemoveFile( m_FileName );
	}
	
	SetResult( VideoResult::SUCCESS );
	m_bMovieCompleted = true;
	
#ifdef LOG_ENCODER_OPERATIONS
	g_pFullFileSystem->Close( m_LogFile );
	m_LogFile = FILESYSTEM_INVALID_HANDLE;
#endif
	
	
	return true;
}



void CQTVideoFileComposer::SetResult( VideoResult_t status )
{
	m_LastResult = status;
}

VideoResult_t CQTVideoFileComposer::GetResult()
{
	return m_LastResult;
}

bool CQTVideoFileComposer::IsReadyToRecord()
{
	return ( m_bComposingMovie && !m_bMovieCompleted );
}


#ifdef ENABLE_EXTERNAL_ENCODER_LOGGING
bool CQTVideoFileComposer::LogMessage(  const char *msg )
{

#ifdef LOG_ENCODER_OPERATIONS
	if ( IS_NOT_EMPTY(msg) && m_LogFile != FILESYSTEM_INVALID_HANDLE )
	{
		g_pFullFileSystem->Write( msg, V_strlen( msg ), m_LogFile );
	}
#endif
	return true;
}
#endif