File: ExportFFmpeg.cpp

package info (click to toggle)
audacity 3.7.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 125,252 kB
  • sloc: cpp: 358,238; ansic: 75,458; lisp: 7,761; sh: 3,410; python: 1,503; xml: 1,385; perl: 854; makefile: 122
file content (1836 lines) | stat: -rw-r--r-- 57,796 bytes parent folder | download
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
/**********************************************************************

   Audacity: A Digital Audio Editor

   ExportFFmpeg.cpp

   Audacity(R) is copyright (c) 1999-2009 Audacity Team.
   License: GPL v2 or later.  See License.txt.

   LRN

******************************************************************//**

\class ExportFFmpeg
\brief Controlling class for FFmpeg exporting.  Creates the options
dialog of the appropriate type, adds tags and invokes the export
function.

*//*******************************************************************/


#include "../FFmpeg.h"
#include "FFmpegFunctions.h"
#include "FifoBuffer.h"

#include <wx/app.h>
#include <wx/log.h>

#include <wx/window.h>
#include <wx/button.h>
#include <wx/textctrl.h>

#include "BasicSettings.h"
#include "Mix.h"
#include "Tags.h"
#include "Track.h"
#include "wxFileNameWrapper.h"

#include "ExportFFmpegOptions.h"
#include "SelectFile.h"
#include "ShuttleGui.h"

#include "ExportPluginHelpers.h"
#include "PlainExportOptionsEditor.h"
#include "FFmpegDefines.h"
#include "ExportOptionsUIServices.h"
#include "ExportPluginRegistry.h"

#if defined(WIN32) && _MSC_VER < 1900
#define snprintf _snprintf
#endif

// Define this to automatically resample audio to the nearest supported sample rate
#define FFMPEG_AUTO_RESAMPLE 1

static int AdjustFormatIndex(int format)
{
   int subFormat = -1;
   for (int i = 0; i <= FMT_OTHER; i++)
   {
      if (ExportFFmpegOptions::fmts[i].compiledIn) subFormat++;
      if (subFormat == format || i == FMT_OTHER)
      {
         subFormat = i;
         break;
      }
   }
   return subFormat;
}

namespace
{

const int iAC3SampleRates[] =
{ 32000, 44100, 48000, 0 };

const int iWMASampleRates[] =
{ 8000, 11025, 16000, 22050, 44100, 0};

///\param rates 0-terminated array
ExportOptionsEditor::SampleRateList ToSampleRateList(const int* rates)
{
   ExportOptionsEditor::SampleRateList list;
   int index = 0;
   while(rates[index] != 0)
      list.push_back(rates[index++]);
   return list;
}

// i18n-hint kbps abbreviates "thousands of bits per second"
TranslatableString n_kbps(int n) { return XO("%d kbps").Format( n ); }
TranslatableString f_kbps( double d ) { return XO("%.2f kbps").Format( d ); }

enum : int
{
   AC3OptionIDBitRate = 0
};

const std::initializer_list<PlainExportOptionsEditor::OptionDesc> AC3Options {
   {
      {
         AC3OptionIDBitRate, XO("Bit Rate"),
         160000,
         ExportOption::TypeEnum,
         {
            32000,
            40000,
            48000,
            56000,
            64000,
            80000,
            96000,
            112000,
            128000,
            160000,
            192000,
            224000,
            256000,
            320000,
            384000,
            448000,
            512000,
            576000,
            640000
         },
         {
            n_kbps( 32 ),
            n_kbps( 40 ),
            n_kbps( 48 ),
            n_kbps( 56 ),
            n_kbps( 64 ),
            n_kbps( 80 ),
            n_kbps( 96 ),
            n_kbps( 112 ),
            n_kbps( 128 ),
            n_kbps( 160 ),
            n_kbps( 192 ),
            n_kbps( 224 ),
            n_kbps( 256 ),
            n_kbps( 320 ),
            n_kbps( 384 ),
            n_kbps( 448 ),
            n_kbps( 512 ),
            n_kbps( 576 ),
            n_kbps( 640 ),
         }
      }, wxT("/FileFormats/AC3BitRate")
   }
};

enum : int
{
   AACOptionIDQuality = 0
};

//NB: user-entered values for AAC are not always followed; mono is clamped to 98-160, stereo 196-320
const std::initializer_list<PlainExportOptionsEditor::OptionDesc> AACOptions {
   {
      {
         AACOptionIDQuality, XO("Quality (kbps)"),
         256,
         ExportOption::TypeRange,
         {98, 320}
      }, wxT("/FileFormats/AACQuality")
   }
};

enum : int
{
   AMRNBOptionIDBitRate = 0
};

const std::initializer_list<PlainExportOptionsEditor::OptionDesc> AMRNBOptions {
   {
      {
         AMRNBOptionIDBitRate, XO("Bit Rate"),
         12200,
         ExportOption::TypeEnum,
         {
            4750,
            5150,
            5900,
            6700,
            7400,
            7950,
            10200,
            12200,
         },
         {
            f_kbps( 4.75 ),
            f_kbps( 5.15 ),
            f_kbps( 5.90 ),
            f_kbps( 6.70 ),
            f_kbps( 7.40 ),
            f_kbps( 7.95 ),
            f_kbps( 10.20 ),
            f_kbps( 12.20 ),
         }
      }, wxT("/FileFormats/AMRNBBitRate")
   }
};

#ifdef SHOW_FFMPEG_OPUS_EXPORT
enum : int
{
   OPUSOptionIDBitRate = 0,
   OPUSOptionIDCompression,
   OPUSOptionIDFrameDuration,
   OPUSOptionIDVBRMode,
   OPUSOptionIDApplication,
   OPUSOptionIDCutoff
};

const std::initializer_list<PlainExportOptionsEditor::OptionDesc> OPUSOptions {
   {
      {
         OPUSOptionIDBitRate, XO("Bit Rate"),
         128000,
         ExportOption::TypeEnum,
         {
            6000,
            8000,
            16000,
            24000,
            32000,
            40000,
            48000,
            64000,
            80000,
            96000,
            128000,
            160000,
            192000,
            256000
         },
         {
            n_kbps( 6 ),
            n_kbps( 8 ),
            n_kbps( 16 ),
            n_kbps( 24 ),
            n_kbps( 32 ),
            n_kbps( 40 ),
            n_kbps( 48 ),
            n_kbps( 64 ),
            n_kbps( 80 ),
            n_kbps( 96 ),
            n_kbps( 128 ),
            n_kbps( 160 ),
            n_kbps( 192 ),
            n_kbps( 256 ),
         }
      }, wxT("/FileFormats/OPUSBitrate")
   },
   {
      {
         OPUSOptionIDCompression, XO("Compression"),
         10,
         ExportOption::TypeRange,
         { 0, 10 }
      }, wxT("/FileFormats/OPUSCompression")
   },
   {
      {
         OPUSOptionIDFrameDuration, XO("Frame Duration"),
         std::string("20"),
         ExportOption::TypeEnum,
         {
            std::string("2.5"),
            std::string("5"),
            std::string("10"),
            std::string("20"),
            std::string("40"),
            std::string("60")
         },
         {
            XO("2.5 ms"),
            XO("5 ms"),
            XO("10 ms"),
            XO("20 ms"),
            XO("40 ms"),
            XO("60 ms"),
         }
      }, wxT("/FileFormats/OPUSFrameDuration")
   },
   {
      {
         OPUSOptionIDVBRMode, XO("Vbr Mode"),
         std::string("on"),
         ExportOption::TypeEnum,
         { std::string("off"), std::string("on"), std::string("constrained") },
         { XO("Off"), XO("On"), XO("Constrained") }
      }, wxT("/FileFormats/OPUSVbrMode")
   },
   {
      {
         OPUSOptionIDApplication, XO("Application"),
         std::string("audio"),
         ExportOption::TypeEnum,
         { std::string("voip"), std::string("audio"), std::string("lowdelay") },
         { XO("VOIP"), XO("Audio"), XO("Low Delay") }
      }, wxT("/FileFormats/OPUSApplication")
   },
   {
      {
         OPUSOptionIDCutoff, XO("Cutoff"),
         std::string("0"),
         ExportOption::TypeEnum,
         {
            std::string("0"),
            std::string("4000"),
            std::string("6000"),
            std::string("8000"),
            std::string("12000"),
            std::string("20000")
         },
         {
            XO("Disabled"),
            XO("Narrowband"),
            XO("Mediumband"),
            XO("Wideband"),
            XO("Super Wideband"),
            XO("Fullband")
         }
      }, wxT("/FileFormats/OPUSCutoff")
   },
};
#endif

enum : int
{
   WMAOptionIDBitRate = 0
};

const std::initializer_list<PlainExportOptionsEditor::OptionDesc> WMAOptions {
   {
      {
         WMAOptionIDBitRate, XO("Bit Rate"),
         128000,
         ExportOption::TypeEnum,
         {
            24000,
            32000,
            40000,
            48000,
            64000,
            80000,
            96000,
            128000,
            160000,
            192000,
            256000,
            320000
         },
         {
            n_kbps(24),
            n_kbps(32),
            n_kbps(40),
            n_kbps(48),
            n_kbps(64),
            n_kbps(80),
            n_kbps(96),
            n_kbps(128),
            n_kbps(160),
            n_kbps(192),
            n_kbps(256),
            n_kbps(320),
         }
      }, wxT("/FileFormats/WMABitRate")
   }
};

const std::vector<ExportOption> FFmpegOptions {
   { FELanguageID, {}, std::string() },
   { FESampleRateID, {}, 0 },
   { FEBitrateID, {}, 0 },
   { FETagID, {}, std::string() },
   { FEQualityID, {}, 0 },
   { FECutoffID, {}, 0},
   { FEBitReservoirID, {}, true },
   { FEVariableBlockLenID, {}, true },
   { FECompLevelID, {}, -1 },
   { FEFrameSizeID, {}, 0 },
   { FELPCCoeffsID, {}, 0 },
   { FEMinPredID, {}, -1 },
   { FEMaxPredID, {}, -1 },
   { FEMinPartOrderID, {}, -1 },
   { FEMaxPartOrderID, {}, -1 },
   { FEPredOrderID, {}, 0 },
   { FEMuxRateID, {}, 0 },
   { FEPacketSizeID, {}, 0 },
   { FECodecID, {}, std::string() },
   { FEFormatID, {}, std::string() }
};

class ExportOptionsFFmpegCustomEditor
   : public ExportOptionsEditor
   , public ExportOptionsUIServices
{
   std::unordered_map<int, ExportValue> mValues;
   std::shared_ptr<FFmpegFunctions> mFFmpeg;
   ExportOptionsEditor::Listener* mListener{};
   //created on-demand
   mutable std::unique_ptr<AVCodecWrapper> mAVCodec;
public:

   ExportOptionsFFmpegCustomEditor(ExportOptionsEditor::Listener* listener = nullptr)
      : mListener(listener)
   {
   }

   void PopulateUI(ShuttleGui& S) override
   {
      CheckFFmpeg(true);
      //Continue anyway, as we do not need ffmpeg functions to build and fill in the UI

      mParent = S.GetParent();

      S.StartHorizontalLay(wxCENTER);
      {
         S.StartVerticalLay(wxCENTER, 0);
         {
            S.AddButton(XXO("Open custom FFmpeg format options"))
               ->Bind(wxEVT_BUTTON, &ExportOptionsFFmpegCustomEditor::OnOpen, this);
            S.StartMultiColumn(2, wxCENTER);
            {
               S.AddPrompt(XXO("Current Format:"));
               mFormat = S.Name(XXO("Current Format:"))
                  .Style(wxTE_READONLY).AddTextBox({}, wxT(""), 25);
               S.AddPrompt(XXO("Current Codec:"));
               mCodec = S.Name(XXO("Current Codec:"))
                  .Style(wxTE_READONLY).AddTextBox({}, wxT(""), 25);
            }
            S.EndMultiColumn();
         }
         S.EndHorizontalLay();
      }
      S.EndHorizontalLay();

      UpdateCodecAndFormat();
   }

   bool TransferDataFromWindow() override
   {
      Load(*gPrefs);
      return true;
   }

   int GetOptionsCount() const override
   {
      return static_cast<int>(FFmpegOptions.size());
   }

   bool GetOption(int index, ExportOption& option) const override
   {
      if(index >= 0 && index < FFmpegOptions.size())
      {
         option = FFmpegOptions[index];
         return true;
      }
      return false;
   }

   bool GetValue(int id, ExportValue& value) const override
   {
      auto it = mValues.find(id);
      if(it != mValues.end())
      {
         value = it->second;
         return true;
      }
      return false;
   }

   bool SetValue(int id, const ExportValue& value) override
   {
      return false;
   }

   SampleRateList GetSampleRateList() const override
   {
      if(!mAVCodec)
      {
         auto it = mValues.find(FECodecID);
         if(it == mValues.end())
            return {};

         const auto codecId = *std::get_if<std::string>(&it->second);
         if (mFFmpeg) {
            mAVCodec = mFFmpeg->CreateEncoder(codecId.c_str());
         }
      }
      if(!mAVCodec)
         return {};

      if(const auto rates = mAVCodec->GetSupportedSamplerates())
         return ToSampleRateList(rates);
      return {};
   }

   void Load(const audacity::BasicSettings& config) override
   {
      mValues[FELanguageID] = std::string(config.Read(wxT("/FileFormats/FFmpegLanguage"), wxT("")).ToUTF8());
      mValues[FESampleRateID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegSampleRate"), 0L));
      mValues[FEBitrateID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegBitRate"), 0L));
      mValues[FETagID] = std::string(config.Read(wxT("/FileFormats/FFmpegTag"), wxT(""))
            .mb_str(wxConvUTF8));
      mValues[FEQualityID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegQuality"), -99999L));
      mValues[FECutoffID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegCutOff"), 0L));
      mValues[FEBitReservoirID] = config.ReadBool(wxT("/FileFormats/FFmpegBitReservoir"), true);
      mValues[FEVariableBlockLenID] = config.ReadBool(wxT("/FileFormats/FFmpegVariableBlockLen"), true);
      mValues[FECompLevelID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegCompLevel"), -1L));
      mValues[FEFrameSizeID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegFrameSize"), 0L));

      mValues[FELPCCoeffsID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegLPCCoefPrec"), 0L));
      mValues[FEMinPredID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegMinPredOrder"), -1L));
      mValues[FEMaxPredID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegMaxPredOrder"), -1L));
      mValues[FEMinPartOrderID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegMinPartOrder"), -1L));
      mValues[FEMaxPartOrderID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegMaxPartOrder"), -1L));
      mValues[FEPredOrderID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegPredOrderMethod"), 0L));
      mValues[FEMuxRateID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegMuxRate"), 0L));
      mValues[FEPacketSizeID] = static_cast<int>(config.Read(wxT("/FileFormats/FFmpegPacketSize"), 0L));
      mValues[FECodecID] = std::string(config.Read(wxT("/FileFormats/FFmpegCodec")));
      mValues[FEFormatID] = std::string(config.Read(wxT("/FileFormats/FFmpegFormat")));
   }

   void Store(audacity::BasicSettings& settings) const override
   {

   }

private:

   bool CheckFFmpeg(bool showError)
   {
      // Show "Locate FFmpeg" dialog
      if(!mFFmpeg)
      {
         mFFmpeg = FFmpegFunctions::Load();
         if (!mFFmpeg)
         {
            FindFFmpegLibs();
            return LoadFFmpeg(showError);
         }
      }
      return true;
   }

   void UpdateCodecAndFormat()
   {
      mFormat->SetValue(gPrefs->Read(wxT("/FileFormats/FFmpegFormat"), wxT("")));
      mCodec->SetValue(gPrefs->Read(wxT("/FileFormats/FFmpegCodec"), wxT("")));
   }

   void OnOpen(const wxCommandEvent&)
   {
      if(!CheckFFmpeg(true))
         return;

   #ifdef __WXMAC__
      // Bug 2077 Must be a parent window on OSX or we will appear behind.
      auto pWin = wxGetTopLevelParent( mParent );
   #else
      // Use GetTopWindow on windows as there is no hWnd with top level parent.
      auto pWin = wxTheApp->GetTopWindow();
   #endif

      ExportFFmpegOptions od(pWin);
      od.ShowModal();
      //ExportFFmpegOptions uses gPrefs to store options
      //Instead we could provide it with instance of wxConfigBase
      //constructed locally and read from it later
      Load(*gPrefs);
      mAVCodec.reset();

      UpdateCodecAndFormat();
      if(mListener)
         mListener->OnSampleRateListChange();
   }

   wxWindow   *mParent {nullptr};
   wxTextCtrl *mFormat {nullptr};
   wxTextCtrl *mCodec {nullptr};
};

}

///Performs actual export
class FFmpegExporter final
{
   static constexpr auto MaxAudioPacketSize { 128 * 1024 };
public:

   FFmpegExporter(std::shared_ptr<FFmpegFunctions> ffmpeg,
      const wxFileNameWrapper& filename,
      int numChannels,
      int subformat);

   /// Format initialization
   bool Init(const char *shortname,
      AudacityProject *project,
      int sampleRate,
      const Tags *metadata,
      const ExportProcessor::Parameters& parameters);

   /// Encodes audio
   bool EncodeAudioFrame(int16_t *pFrame, size_t frameSize);

   /// Flushes audio encoder
   bool Finalize();

   std::unique_ptr<Mixer> CreateMixer(
      const AudacityProject& project, bool selectionOnly, double startTime,
      double stopTime, MixerOptions::Downmix* mixerSpec);

private:

   /// Writes metadata
   bool AddTags(const Tags *metadata);

   /// Sets individual metadata values
   void SetMetadata(const Tags *tags, const char *name, const wxChar *tag);

   /// Check whether or not current project sample rate is compatible with the export codec
   bool CheckSampleRate(int rate, int lowrate, int highrate, const int *sampRates);

   /// Asks user to resample the project or cancel the export procedure
   int AskResample(int bitrate, int rate, int lowrate, int highrate, const int *sampRates);

   /// Codec initialization
   bool InitCodecs(int sampleRate,
      const ExportProcessor::Parameters& parameters);

   void WritePacket(AVPacketWrapper& packet);

   int EncodeAudio(AVPacketWrapper& pkt,
      int16_t* audio_samples,
      int nb_samples);

   std::shared_ptr<FFmpegFunctions> mFFmpeg;

   std::unique_ptr<AVOutputFormatWrapper> mEncFormatDesc;       // describes our output file to libavformat
   int mDefaultFrameSize {};
   std::unique_ptr<AVStreamWrapper> mEncAudioStream; // the output audio stream (may remain NULL)
   int mEncAudioFifoOutBufSize {};

   wxFileNameWrapper mName;

   int               mSubFormat{};
   int               mBitRate{};
   int               mSampleRate{};
   unsigned          mChannels{};
   bool              mSupportsUTF8{true};

   // Smart pointer fields, their order is the reverse in which they are reset in FreeResources():
   std::unique_ptr<FifoBuffer> mEncAudioFifo; // FIFO to write incoming audio samples into
   AVDataBuffer<int16_t> mEncAudioFifoOutBuf; // buffer to read _out_ of the FIFO into
   std::unique_ptr<AVFormatContextWrapper> mEncFormatCtx; // libavformat's context for our output file
   std::unique_ptr<AVCodecContextWrapper> mEncAudioCodecCtx;    // the encoder for the output audio stream
};

class FFmpegExportProcessor final : public ExportProcessor
{
   std::shared_ptr<FFmpegFunctions> mFFmpeg;
   struct
   {
      //same index as in GetFormatInfo, use AdjustFormatIndex to convert it to FFmpegExposedFormat
      int subformat;
      TranslatableString status;
      double t0;
      double t1;
      std::unique_ptr<Mixer> mixer;
      std::unique_ptr<FFmpegExporter> exporter;
   } context;

public:
   FFmpegExportProcessor(std::shared_ptr<FFmpegFunctions> ffmpeg, int format);

   bool Initialize(AudacityProject& project,
      const Parameters& parameters,
      const wxFileNameWrapper& filename,
      double t0, double t1, bool selectedOnly,
      double sampleRate, unsigned channels,
      MixerOptions::Downmix* mixerSpec,
      const Tags* tags) override;

   ExportResult Process(ExportProcessorDelegate& delegate) override;

};

class ExportFFmpeg final : public ExportPlugin
{
public:

   ExportFFmpeg();
   ~ExportFFmpeg() override;

   std::unique_ptr<ExportOptionsEditor>
   CreateOptionsEditor(int format, ExportOptionsEditor::Listener* listener) const override;

   int GetFormatCount() const override;
   FormatInfo GetFormatInfo(int index) const override;

   /// Callback, called from GetFilename
   bool CheckFileName(wxFileName &filename, int format = 0) const override;

   std::unique_ptr<ExportProcessor> CreateProcessor(int format) const override;

private:
   mutable std::shared_ptr<FFmpegFunctions> mFFmpeg;

   std::vector<FormatInfo> mFormatInfos;
};

FFmpegExporter::FFmpegExporter(std::shared_ptr<FFmpegFunctions> ffmpeg,
   const wxFileNameWrapper& filename,
   int numChannels,
   int subFormat)
   : mFFmpeg(std::move(ffmpeg))
   , mName(filename)
   , mChannels(numChannels)
   , mSubFormat(subFormat)
{
   if (!mFFmpeg) {
      mFFmpeg = FFmpegFunctions::Load();
   }
}

std::unique_ptr<Mixer> FFmpegExporter::CreateMixer(
   const AudacityProject& project, bool selectionOnly, double startTime,
   double stopTime, MixerOptions::Downmix* mixerSpec)
{
   return ExportPluginHelpers::CreateMixer(
      project, selectionOnly, startTime, stopTime, mChannels, mDefaultFrameSize,
      true, mSampleRate, int16Sample, mixerSpec);
}


ExportFFmpeg::ExportFFmpeg()
{
   mFFmpeg = FFmpegFunctions::Load();

   int avfver = mFFmpeg ? mFFmpeg->AVFormatVersion.GetIntVersion() : 0;

   int newfmt;
   // Adds export types from the export type list
   for (newfmt = 0; newfmt < FMT_LAST; newfmt++)
   {
      wxString shortname(ExportFFmpegOptions::fmts[newfmt].shortname);
      // Don't hide export types when there's no av-libs, and don't hide FMT_OTHER
      if (newfmt < FMT_OTHER && mFFmpeg)
      {
         // Format/Codec support is compiled in?
         auto avoformat = mFFmpeg->GuessOutputFormat(shortname.mb_str(), nullptr, nullptr);
         auto avcodec = mFFmpeg->CreateEncoder(mFFmpeg->GetAVCodecID(ExportFFmpegOptions::fmts[newfmt].codecid));

         if (avoformat == NULL || avcodec == NULL)
         {
            ExportFFmpegOptions::fmts[newfmt].compiledIn = false;
            continue;
         }
      }
      FormatInfo formatInfo {};
      formatInfo.format = ExportFFmpegOptions::fmts[newfmt].name;
      formatInfo.extensions.push_back(ExportFFmpegOptions::fmts[newfmt].extension);
      // For some types add other extensions
      switch(newfmt)
      {
      case FMT_M4A:
         formatInfo.extensions.push_back(wxT("3gp"));
         formatInfo.extensions.push_back(wxT("m4r"));
         formatInfo.extensions.push_back(wxT("mp4"));
         break;
      case FMT_WMA2:
         formatInfo.extensions.push_back(wxT("asf"));
         formatInfo.extensions.push_back(wxT("wmv"));
         break;
      default:
         break;
      }
      formatInfo.maxChannels = ExportFFmpegOptions::fmts[newfmt].maxchannels;
      formatInfo.description = ExportFFmpegOptions::fmts[newfmt].description;

      const int canmeta = ExportFFmpegOptions::fmts[newfmt].canmetadata;
      formatInfo.canMetaData = canmeta && (canmeta == AV_CANMETA || canmeta <= avfver);

      mFormatInfos.push_back(std::move(formatInfo));
   }
}

ExportFFmpeg::~ExportFFmpeg() = default;

std::unique_ptr<ExportOptionsEditor>
ExportFFmpeg::CreateOptionsEditor(int format, ExportOptionsEditor::Listener* listener) const
{
   switch(AdjustFormatIndex(format))
   {
   case FMT_M4A:
      return std::make_unique<PlainExportOptionsEditor>(AACOptions, listener);
   case FMT_AC3:
      return std::make_unique<PlainExportOptionsEditor>(
         AC3Options,
         ToSampleRateList(iAC3SampleRates),
         listener);
   case FMT_AMRNB:
      return std::make_unique<PlainExportOptionsEditor>(
         AMRNBOptions,
         ExportOptionsEditor::SampleRateList {8000},
         listener);
#ifdef SHOW_FFMPEG_OPUS_EXPORT
   case FMT_OPUS:
      return std::make_unique<PlainExportOptionsEditor>(OPUSOptions, listener);
#endif
   case FMT_WMA2:
      return std::make_unique<PlainExportOptionsEditor>(
         WMAOptions,
         ToSampleRateList(iWMASampleRates),
         listener);
   case FMT_OTHER:
      return std::make_unique<ExportOptionsFFmpegCustomEditor>(listener);
   }
   return {};
}

int ExportFFmpeg::GetFormatCount() const
{
   return static_cast<int>(mFormatInfos.size());
}

FormatInfo ExportFFmpeg::GetFormatInfo(int index) const
{
   if(index >= 0 && index < mFormatInfos.size())
      return mFormatInfos[index];
   return mFormatInfos[FMT_OTHER];
}

bool ExportFFmpeg::CheckFileName(wxFileName & WXUNUSED(filename), int WXUNUSED(format)) const
{
   bool result = true;

   // Show "Locate FFmpeg" dialog
   mFFmpeg = FFmpegFunctions::Load();
   if (!mFFmpeg)
   {
      FindFFmpegLibs();
      mFFmpeg = FFmpegFunctions::Load();

      return LoadFFmpeg(true);
   }

   return result;
}

std::unique_ptr<ExportProcessor> ExportFFmpeg::CreateProcessor(int format) const
{
   return std::make_unique<FFmpegExportProcessor>(mFFmpeg, format);
}


bool FFmpegExporter::Init(const char *shortname,
                        AudacityProject *project,
                        int sampleRate,
                        const Tags *metadata,
                        const ExportProcessor::Parameters& parameters)
{
   if (!mFFmpeg)
      return false;

   // See if libavformat has modules that can write our output format. If so, mEncFormatDesc
   // will describe the functions used to write the format (used internally by libavformat)
   // and the default video/audio codecs that the format uses.
   const auto path = mName.GetFullPath();
   if ((mEncFormatDesc = mFFmpeg->GuessOutputFormat(shortname, OSINPUT(path), nullptr)) == nullptr)
   {
      throw ExportException(_("FFmpeg : ERROR - Can't determine format description for file \"%s\".").Format(path));
   }

   // mEncFormatCtx is used by libavformat to carry around context data re our output file.
   mEncFormatCtx = mFFmpeg->CreateAVFormatContext();
   if (!mEncFormatCtx)
   {
      throw ExportException(_("FFmpeg : ERROR - Can't allocate output format context."));
   }

   // Initialise the output format context.
   mEncFormatCtx->SetOutputFormat(mFFmpeg->CreateAVOutputFormatWrapper(mEncFormatDesc->GetWrappedValue()));
   mEncFormatCtx->SetFilename(OSINPUT(path));

   // At the moment Audacity can export only one audio stream
   if ((mEncAudioStream = mEncFormatCtx->CreateStream()) == nullptr)
   {
      throw ExportException(_("FFmpeg : ERROR - Can't add audio stream to output file \"%s\"."));
   }

   // Documentation for avformat_new_stream says
   // "User is required to call avcodec_close() and avformat_free_context() to clean
   // up the allocation by avformat_new_stream()."

   // We use smart pointers that ensure these cleanups either in their destructors or
   // sooner if they are reset.  These are std::unique_ptr with nondefault deleter
   // template parameters.

   // mEncFormatCtx takes care of avformat_free_context(), so
   // mEncAudioStream can be a plain pointer.

   // mEncAudioCodecCtx now becomes responsible for closing the codec:
   mEncAudioCodecCtx = mEncAudioStream->GetAVCodecContext();
   mEncAudioStream->SetId(0);

   // Open the output file.
   if (!(mEncFormatDesc->GetFlags() & AUDACITY_AVFMT_NOFILE))
   {
      AVIOContextWrapper::OpenResult result =
         mEncFormatCtx->OpenOutputContext(path);

      if (result != AVIOContextWrapper::OpenResult::Success)
      {
         throw ExportException(_("FFmpeg : ERROR - Can't open output file \"%s\" to write. Error code is %d.")
            .Format(path, static_cast<int>(result)));
      }
   }

   // Open the audio stream's codec and initialise any stream related data.
   if(!InitCodecs(sampleRate, parameters))
      return false;

   if (mEncAudioStream->SetParametersFromContext(*mEncAudioCodecCtx) < 0)
      return false;

   if (metadata == NULL)
      metadata = &Tags::Get( *project );

   // Add metadata BEFORE writing the header.
   // At the moment that works with ffmpeg-git and ffmpeg-0.5 for MP4.
   const auto canmeta = ExportFFmpegOptions::fmts[mSubFormat].canmetadata;
   const auto avfver = mFFmpeg->AVFormatVersion.GetIntVersion();
   if (canmeta && (canmeta == AV_CANMETA || canmeta <= avfver))
   {
      mSupportsUTF8 = ExportFFmpegOptions::fmts[mSubFormat].canutf8;
      AddTags(metadata);
   }

   // Write headers to the output file.
   int err =
      mFFmpeg->avformat_write_header(mEncFormatCtx->GetWrappedValue(), nullptr);

   if (err < 0)
   {
      throw ExportException(XO("FFmpeg : ERROR - Can't write headers to output file \"%s\". Error code is %d.")
         .Format( path, err )
         .Translation());
   }

   return true;
}

bool FFmpegExporter::CheckSampleRate(int rate, int lowrate, int highrate, const int *sampRates)
{
   if (lowrate && highrate)
   {
      if (rate < lowrate || rate > highrate)
      {
         return false;
      }
   }

   if (sampRates)
   {
      for (int i = 0; sampRates[i] > 0; i++)
      {
         if (rate == sampRates[i])
         {
            return true;
         }
      }
   }

   return false;
}

bool FFmpegExporter::InitCodecs(int sampleRate,
                                const ExportProcessor::Parameters& parameters)
{
   std::unique_ptr<AVCodecWrapper> codec;

   AVDictionaryWrapper options(*mFFmpeg);

   // Get the sample rate from the passed settings if we haven't set it before.
   // Doing this only when not set allows us to carry the sample rate from one
   // iteration of ExportMultiple to the next.  This prevents multiple resampling
   // dialogs in the event the codec can't support the specified rate.
   if (!mSampleRate)
   {
      //TODO: Does not work with export multiple any more...
      mSampleRate = sampleRate;
   }

   // Configure the audio stream's codec context.

   const auto codecID = ExportFFmpegOptions::fmts[mSubFormat].codecid;

   mEncAudioCodecCtx->SetGlobalQuality(-99999); //quality mode is off by default;

   // Each export type has its own settings
   switch (mSubFormat)
   {
   case FMT_M4A:
   {
      int q = ExportPluginHelpers::GetParameterValue(parameters, AACOptionIDQuality, -99999);

      q = wxClip( q, 98 * mChannels, 160 * mChannels );
      // Set bit rate to between 98 kbps and 320 kbps (if two channels)
      mEncAudioCodecCtx->SetBitRate(q * 1000);
      mEncAudioCodecCtx->SetProfile(AUDACITY_FF_PROFILE_AAC_LOW);
      mEncAudioCodecCtx->SetCutoff(0);

      break;
   }
   case FMT_AC3:
      mEncAudioCodecCtx->SetBitRate(ExportPluginHelpers::GetParameterValue(parameters, AC3OptionIDBitRate, 192000));
      if (!CheckSampleRate(
             mSampleRate, iAC3SampleRates[0],
             iAC3SampleRates[2],
             &iAC3SampleRates[0]))
      {
         mSampleRate = AskResample(
            mEncAudioCodecCtx->GetBitRate(), mSampleRate,
            iAC3SampleRates[0],
            iAC3SampleRates[2],
            &iAC3SampleRates[0]);
      }
      break;
   case FMT_AMRNB:
      mSampleRate = 8000;
      mEncAudioCodecCtx->SetBitRate(ExportPluginHelpers::GetParameterValue(parameters, AMRNBOptionIDBitRate, 12200));
      break;
#ifdef SHOW_FFMPEG_OPUS_EXPORT
   case FMT_OPUS:
      options.Set("b", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDBitRate, "128000"), 0);
      options.Set("vbr", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDVBRMode, "on"), 0);
      options.Set("compression_level", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDCompression, "10"), 0);
      options.Set("frame_duration", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDFrameDuration, "20"), 0);
      options.Set("application", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDApplication, "audio"), 0);
      options.Set("cutoff", ExportPluginHelpers::GetParameterValue<std::string>(parameters, OPUSOptionIDCutoff, "0"), 0);
      options.Set("mapping_family", mChannels <= 2 ? "0" : "255", 0);
      break;
#endif
   case FMT_WMA2:
      mEncAudioCodecCtx->SetBitRate(ExportPluginHelpers::GetParameterValue(parameters, WMAOptionIDBitRate, 198000));
      if (!CheckSampleRate(
             mSampleRate, iWMASampleRates[0],
             iWMASampleRates[4],
             &iWMASampleRates[0]))
      {
         mSampleRate = AskResample(
            mEncAudioCodecCtx->GetBitRate(), mSampleRate,
            iWMASampleRates[0],
            iWMASampleRates[4],
            &iWMASampleRates[0]);
      }
      break;
   case FMT_OTHER:
   {
      AVDictionaryWrapper streamMetadata = mEncAudioStream->GetMetadata();
      streamMetadata.Set(
         "language",
         ExportPluginHelpers::GetParameterValue<std::string>(parameters, FELanguageID), 0);

      mEncAudioStream->SetMetadata(streamMetadata);

      mEncAudioCodecCtx->SetSampleRate(
         ExportPluginHelpers::GetParameterValue(parameters, FESampleRateID, 0));

      if (mEncAudioCodecCtx->GetSampleRate() != 0)
         mSampleRate = mEncAudioCodecCtx->GetSampleRate();

      mEncAudioCodecCtx->SetBitRate(
         ExportPluginHelpers::GetParameterValue(parameters, FEBitrateID, 0));

      mEncAudioCodecCtx->SetCodecTagFourCC(
         ExportPluginHelpers::GetParameterValue<std::string>(parameters, FETagID).c_str());

      mEncAudioCodecCtx->SetGlobalQuality(
         ExportPluginHelpers::GetParameterValue(parameters, FEQualityID, -99999));
      mEncAudioCodecCtx->SetCutoff(
         ExportPluginHelpers::GetParameterValue(parameters, FECutoffID, 0));
      mEncAudioCodecCtx->SetFlags2(0);

      if (ExportPluginHelpers::GetParameterValue(parameters, FEBitReservoirID, true))
         options.Set("reservoir", "1", 0);

      if (ExportPluginHelpers::GetParameterValue(parameters, FEVariableBlockLenID, true))
         mEncAudioCodecCtx->SetFlags2(
            mEncAudioCodecCtx->GetFlags2() | 0x0004); // WMA only?

      mEncAudioCodecCtx->SetCompressionLevel(
         ExportPluginHelpers::GetParameterValue(parameters, FECompLevelID, -1));
      mEncAudioCodecCtx->SetFrameSize(
         ExportPluginHelpers::GetParameterValue(parameters, FEFrameSizeID, 0));

      // FIXME The list of supported options for the selected encoder should be
      // extracted instead of a few hardcoded

      options.Set(
         "lpc_coeff_precision",
         ExportPluginHelpers::GetParameterValue(parameters, FELPCCoeffsID, 0));
      options.Set(
         "min_prediction_order",
         ExportPluginHelpers::GetParameterValue(parameters, FEMinPredID, -1));
      options.Set(
         "max_prediction_order",
         ExportPluginHelpers::GetParameterValue(parameters, FEMaxPredID, -1));
      options.Set(
         "min_partition_order",
         ExportPluginHelpers::GetParameterValue(parameters, FEMinPartOrderID, -1));
      options.Set(
         "max_partition_order",
         ExportPluginHelpers::GetParameterValue(parameters, FEMaxPartOrderID, -1));
      options.Set(
         "prediction_order_method",
         ExportPluginHelpers::GetParameterValue(parameters, FEPredOrderID, 0));
      options.Set(
         "muxrate",
         ExportPluginHelpers::GetParameterValue(parameters, FEMuxRateID, 0));

      mEncFormatCtx->SetPacketSize(
         ExportPluginHelpers::GetParameterValue(parameters, FEPacketSizeID, 0));

      codec = mFFmpeg->CreateEncoder(
         ExportPluginHelpers::GetParameterValue<std::string>(parameters, FECodecID).c_str());

      if (!codec)
         codec = mFFmpeg->CreateEncoder(mEncFormatDesc->GetAudioCodec());
   }
      break;
   default:
      return false;
   }

   // This happens if user refused to resample the project
   if (mSampleRate == 0) return false;

   if (mEncAudioCodecCtx->GetGlobalQuality() >= 0)
   {
      mEncAudioCodecCtx->SetFlags(
         mEncAudioCodecCtx->GetFlags() | AUDACITY_AV_CODEC_FLAG_QSCALE);
   }
   else
   {
      mEncAudioCodecCtx->SetGlobalQuality(0);
   }

   mEncAudioCodecCtx->SetGlobalQuality(mEncAudioCodecCtx->GetGlobalQuality() * AUDACITY_FF_QP2LAMBDA);
   mEncAudioCodecCtx->SetSampleRate(mSampleRate);
   mEncAudioCodecCtx->SetChannelLayout(mFFmpeg->CreateDefaultChannelLayout(mChannels).get());
   mEncAudioCodecCtx->SetTimeBase({ 1, mSampleRate });
   mEncAudioCodecCtx->SetSampleFmt(static_cast<AVSampleFormatFwd>(AUDACITY_AV_SAMPLE_FMT_S16));
   mEncAudioCodecCtx->SetStrictStdCompliance(
      AUDACITY_FF_COMPLIANCE_EXPERIMENTAL);

   if (codecID == AUDACITY_AV_CODEC_ID_AC3)
   {
      // As of Jan 4, 2011, the default AC3 encoder only accept SAMPLE_FMT_FLT samples.
      // But, currently, Audacity only supports SAMPLE_FMT_S16.  So, for now, look for the
      // "older" AC3 codec.  this is not a proper solution, but will suffice until other
      // encoders no longer support SAMPLE_FMT_S16.
      codec = mFFmpeg->CreateEncoder("ac3_fixed");
   }

   if (!codec)
   {
      codec = mFFmpeg->CreateEncoder(mFFmpeg->GetAVCodecID(codecID));
   }

   // Is the required audio codec compiled into libavcodec?
   if (codec == NULL)
   {
      /* i18n-hint: "codec" is short for a "coder-decoder" algorithm */
      throw ExportException(XO("FFmpeg cannot find audio codec 0x%x.\nSupport for this codec is probably not compiled in.")
                  .Format(static_cast<const unsigned int>(codecID.value))
                  .Translation());
   }

   if (codec->GetSampleFmts()) {
      for (int i = 0; codec->GetSampleFmts()[i] != AUDACITY_AV_SAMPLE_FMT_NONE; i++)
      {
         AVSampleFormatFwd fmt = codec->GetSampleFmts()[i];

         if (
            fmt == AUDACITY_AV_SAMPLE_FMT_U8 ||
            fmt == AUDACITY_AV_SAMPLE_FMT_U8P ||
            fmt == AUDACITY_AV_SAMPLE_FMT_S16 ||
            fmt == AUDACITY_AV_SAMPLE_FMT_S16P ||
            fmt == AUDACITY_AV_SAMPLE_FMT_S32 ||
            fmt == AUDACITY_AV_SAMPLE_FMT_S32P ||
            fmt == AUDACITY_AV_SAMPLE_FMT_FLT ||
            fmt == AUDACITY_AV_SAMPLE_FMT_FLTP)
         {
            mEncAudioCodecCtx->SetSampleFmt(fmt);
         }

         if (
            fmt == AUDACITY_AV_SAMPLE_FMT_S16 ||
            fmt == AUDACITY_AV_SAMPLE_FMT_S16P)
            break;
      }
   }

   if (codec->GetSupportedSamplerates())
   {
      // Workaround for crash in bug #2378.  Proper fix is to get a newer version of FFmpeg.
      if (codec->GetId() == mFFmpeg->GetAVCodecID(AUDACITY_AV_CODEC_ID_AAC))
      {
         std::vector<int> rates;
         int i = 0;

         while (codec->GetSupportedSamplerates()[i] &&
                codec->GetSupportedSamplerates()[i] != 7350)
         {
            rates.push_back(codec->GetSupportedSamplerates()[i++]);
         }

         rates.push_back(0);

         if (!CheckSampleRate(mSampleRate, 0, 0, rates.data()))
         {
            mSampleRate = AskResample(0, mSampleRate, 0, 0, rates.data());
            mEncAudioCodecCtx->SetSampleRate(mSampleRate);
         }
      }
      else
      {
         if (!CheckSampleRate(
                mSampleRate, 0, 0, codec->GetSupportedSamplerates()))
         {
            mSampleRate = AskResample(
               0, mSampleRate, 0, 0, codec->GetSupportedSamplerates());
            mEncAudioCodecCtx->SetSampleRate(mSampleRate);
         }
      }

      // This happens if user refused to resample the project
      if (mSampleRate == 0)
      {
         return false;
      }
   }

   if (mEncFormatCtx->GetOutputFormat()->GetFlags() & AUDACITY_AVFMT_GLOBALHEADER)
   {
      mEncAudioCodecCtx->SetFlags(mEncAudioCodecCtx->GetFlags() | AUDACITY_AV_CODEC_FLAG_GLOBAL_HEADER);
      mEncFormatCtx->SetFlags(mEncFormatCtx->GetFlags() | AUDACITY_AV_CODEC_FLAG_GLOBAL_HEADER);
   }

   // Open the codec.
   int rc = mEncAudioCodecCtx->Open(codec.get(), &options);
   if (rc < 0)
   {
      TranslatableString errmsg;

      switch (rc)
      {
      case AUDACITY_AVERROR(EPERM):
         errmsg = XO("The codec reported a generic error (EPERM)");
         break;
      case AUDACITY_AVERROR(EINVAL):
         errmsg = XO("The codec reported an invalid parameter (EINVAL)");
         break;
      default:
         char buf[64];
         mFFmpeg->av_strerror(rc, buf, sizeof(buf));
         errmsg = Verbatim(buf);
      }

      /* i18n-hint: "codec" is short for a "coder-decoder" algorithm */
      throw ExportException(XO("Can't open audio codec \"%s\" (0x%x)\n\n%s")
         .Format(codec->GetName(), codecID.value, errmsg)
         .Translation());
   }

   mDefaultFrameSize = mEncAudioCodecCtx->GetFrameSize();

   if (mDefaultFrameSize == 0)
      mDefaultFrameSize = 1024; // arbitrary non zero value;

   wxLogDebug(
      wxT("FFmpeg : Audio Output Codec Frame Size: %d samples."),
      mEncAudioCodecCtx->GetFrameSize());

   // The encoder may require a minimum number of raw audio samples for each encoding but we can't
   // guarantee we'll get this minimum each time an audio frame is decoded from the input file so
   // we use a FIFO to store up incoming raw samples until we have enough for one call to the codec.
   mEncAudioFifo = std::make_unique<FifoBuffer>(mDefaultFrameSize * mChannels * sizeof(int16_t));

   mEncAudioFifoOutBufSize = 2*MaxAudioPacketSize;
   // Allocate a buffer to read OUT of the FIFO into. The FIFO maintains its own buffer internally.
   mEncAudioFifoOutBuf = mFFmpeg->CreateMemoryBuffer<int16_t>(mEncAudioFifoOutBufSize);

   if (mEncAudioFifoOutBuf.empty())
   {
      throw ExportException(_("FFmpeg : ERROR - Can't allocate buffer to read into from audio FIFO."));
   }

   return true;
}

void FFmpegExporter::WritePacket(AVPacketWrapper& pkt)
{
   // Set presentation time of frame (currently in the codec's timebase) in the
   // stream timebase.
   if (pkt.GetPresentationTimestamp() != AUDACITY_AV_NOPTS_VALUE)
      pkt.RescalePresentationTimestamp(
         mEncAudioCodecCtx->GetTimeBase(), mEncAudioStream->GetTimeBase());

   if (pkt.GetDecompressionTimestamp() != AUDACITY_AV_NOPTS_VALUE)
      pkt.RescaleDecompressionTimestamp(
         mEncAudioCodecCtx->GetTimeBase(), mEncAudioStream->GetTimeBase());

   if (pkt.GetDuration() > 0)
      pkt.RescaleDuration(
         mEncAudioCodecCtx->GetTimeBase(), mEncAudioStream->GetTimeBase());

   if (
      mFFmpeg->av_interleaved_write_frame(
         mEncFormatCtx->GetWrappedValue(), pkt.GetWrappedValue()) != 0)
   {
      throw ExportException(_("FFmpeg : ERROR - Couldn't write audio frame to output file."));
   }
}

// Returns 0 if no more output, 1 if more output, negative if error
int FFmpegExporter::EncodeAudio(AVPacketWrapper& pkt, int16_t* audio_samples, int nb_samples)
{
   // Assume *pkt is already initialized.

   int i, ch, buffer_size, ret, got_output = 0;
   AVDataBuffer<uint8_t> samples;

   std::unique_ptr<AVFrameWrapper> frame;

   if (audio_samples) {
      frame = mFFmpeg->CreateAVFrameWrapper();

      if (!frame)
         return AUDACITY_AVERROR(ENOMEM);

      frame->SetSamplesCount(nb_samples);
      frame->SetFormat(mEncAudioCodecCtx->GetSampleFmt());
      frame->SetChannelLayout(mEncAudioCodecCtx->GetChannelLayout());

      buffer_size = mFFmpeg->av_samples_get_buffer_size(
         NULL, mEncAudioCodecCtx->GetChannels(), nb_samples,
         mEncAudioCodecCtx->GetSampleFmt(), 0);

      if (buffer_size < 0) {
         throw ExportException(_("FFmpeg : ERROR - Could not get sample buffer size"));
      }

      samples = mFFmpeg->CreateMemoryBuffer<uint8_t>(buffer_size);

      if (samples.empty()) {
         throw ExportException(_("FFmpeg : ERROR - Could not allocate bytes for samples buffer"));
      }
      /* setup the data pointers in the AVFrame */
      ret = mFFmpeg->avcodec_fill_audio_frame(
         frame->GetWrappedValue(), mEncAudioCodecCtx->GetChannels(),
         mEncAudioCodecCtx->GetSampleFmt(), samples.data(), buffer_size, 0);

      if (ret < 0) {
         throw ExportException(_("FFmpeg : ERROR - Could not setup audio frame"));
      }

      const int channelsCount = mEncAudioCodecCtx->GetChannels();

      for (ch = 0; ch < mEncAudioCodecCtx->GetChannels(); ch++)
      {
         for (i = 0; i < nb_samples; i++) {
            switch (static_cast<AudacityAVSampleFormat>(
               mEncAudioCodecCtx->GetSampleFmt()))
            {
            case AUDACITY_AV_SAMPLE_FMT_U8:
               ((uint8_t*)(frame->GetData(0)))[ch + i*channelsCount] = audio_samples[ch + i*channelsCount]/258 + 128;
               break;
            case AUDACITY_AV_SAMPLE_FMT_U8P:
               ((uint8_t*)(frame->GetData(ch)))[i] = audio_samples[ch + i*channelsCount]/258 + 128;
               break;
            case AUDACITY_AV_SAMPLE_FMT_S16:
               ((int16_t*)(frame->GetData(0)))[ch + i*channelsCount] = audio_samples[ch + i*channelsCount];
               break;
            case AUDACITY_AV_SAMPLE_FMT_S16P:
               ((int16_t*)(frame->GetData(ch)))[i] = audio_samples[ch + i*channelsCount];
               break;
            case AUDACITY_AV_SAMPLE_FMT_S32:
               ((int32_t*)(frame->GetData(0)))[ch + i*channelsCount] = audio_samples[ch + i*channelsCount]<<16;
               break;
            case AUDACITY_AV_SAMPLE_FMT_S32P:
               ((int32_t*)(frame->GetData(ch)))[i] = audio_samples[ch + i*channelsCount]<<16;
               break;
            case AUDACITY_AV_SAMPLE_FMT_FLT:
               ((float*)(frame->GetData(0)))[ch + i*channelsCount] = audio_samples[ch + i*channelsCount] / 32767.0;
               break;
            case AUDACITY_AV_SAMPLE_FMT_FLTP:
               ((float*)(frame->GetData(ch)))[i] = audio_samples[ch + i*channelsCount] / 32767.;
               break;
            default:
               wxASSERT(false);
               break;
            }
         }
      }
   }

   pkt.ResetData();

   pkt.SetStreamIndex(mEncAudioStream->GetIndex());

   if (mFFmpeg->avcodec_send_frame != nullptr)
   {
      ret = mFFmpeg->avcodec_send_frame(
         mEncAudioCodecCtx->GetWrappedValue(),
         frame ? frame->GetWrappedValue() : nullptr);

      while (ret >= 0)
      {
         ret = mFFmpeg->avcodec_receive_packet(
            mEncAudioCodecCtx->GetWrappedValue(), pkt.GetWrappedValue());

         if (ret == AUDACITY_AVERROR(EAGAIN) || ret == AUDACITY_AVERROR_EOF)
         {
            ret = 0;
            break;
         }
         else if (ret < 0)
            break;

         WritePacket(pkt);

         got_output = true;
      }
   }
   else
   {
      ret = mFFmpeg->avcodec_encode_audio2(
         mEncAudioCodecCtx->GetWrappedValue(), pkt.GetWrappedValue(),
         frame ? frame->GetWrappedValue() : nullptr, &got_output);

      if (ret == 0)
      {
         WritePacket(pkt);
      }
   }

   if (ret < 0 && ret != AUDACITY_AVERROR_EOF) {

      char buf[64];
      mFFmpeg->av_strerror(ret, buf, sizeof(buf));
      wxLogDebug(buf);

      throw ExportException(_("FFmpeg : ERROR - encoding frame failed"));
   }

   pkt.ResetTimestamps(); // We don't set frame timestamps thus don't trust the AVPacket timestamps

   return got_output;
}


bool FFmpegExporter::Finalize()
{
   // Flush the audio FIFO and encoder.
   for (;;)
   {
      std::unique_ptr<AVPacketWrapper> pkt = mFFmpeg->CreateAVPacketWrapper();

      const auto nFifoBytes =
         mEncAudioFifo->GetAvailable(); // any bytes left in audio FIFO?

      int encodeResult = 0;

      // Flush the audio FIFO first if necessary. It won't contain a _full_ audio frame because
      // if it did we'd have pulled it from the FIFO during the last encodeAudioFrame() call
      if (nFifoBytes > 0)
      {
         const int nAudioFrameSizeOut = mDefaultFrameSize * mEncAudioCodecCtx->GetChannels() * sizeof(int16_t);

         if (nAudioFrameSizeOut > mEncAudioFifoOutBufSize || nFifoBytes > mEncAudioFifoOutBufSize) {
            throw ExportException(_("FFmpeg : ERROR - Too much remaining data."));
         }

         // We have an incomplete buffer of samples left, encode it.
         // If codec supports CODEC_CAP_SMALL_LAST_FRAME, we can feed it with smaller frame
         // Or if frame_size is 1, then it's some kind of PCM codec, they don't have frames and will be fine with the samples
         // Otherwise we'll send a full frame of audio + silence padding to ensure all audio is encoded
         int frame_size = mDefaultFrameSize;
         if (
            mEncAudioCodecCtx->GetCodec()->GetCapabilities() &
               AUDACITY_AV_CODEC_CAP_SMALL_LAST_FRAME ||
            frame_size == 1)
         {
            frame_size = nFifoBytes /
                         (mEncAudioCodecCtx->GetChannels() * sizeof(int16_t));
         }

         wxLogDebug(wxT("FFmpeg : Audio FIFO still contains %lld bytes, writing %d sample frame ..."),
            nFifoBytes, frame_size);

         // Fill audio buffer with zeroes. If codec tries to read the whole buffer,
         // it will just read silence. If not - who cares?
         memset(mEncAudioFifoOutBuf.data(), 0, mEncAudioFifoOutBufSize);
         //const AVCodec *codec = mEncAudioCodecCtx->codec;

         // Pull the bytes out from the FIFO and feed them to the encoder.
         if (mEncAudioFifo->Read(mEncAudioFifoOutBuf.data(), nFifoBytes) == nFifoBytes)
         {
            encodeResult = EncodeAudio(*pkt, mEncAudioFifoOutBuf.data(), frame_size);
         }
         else
         {
            wxLogDebug(wxT("FFmpeg : Reading from Audio FIFO failed, aborting"));
            // TODO: more precise message
            throw ExportErrorException("FFmpeg:825");
         }
      }
      else
      {
         // Fifo is empty, flush encoder. May be called multiple times.
         encodeResult =
            EncodeAudio(*pkt.get(), nullptr, 0);
      }

      if (encodeResult < 0) {
         // TODO: more precise message
         throw ExportErrorException("FFmpeg:837");
      }
      else if (encodeResult == 0)
         break;
   }

   // Write any file trailers.
   if (mFFmpeg->av_write_trailer(mEncFormatCtx->GetWrappedValue()) != 0)
   {
      // TODO: more precise message
      throw ExportErrorException("FFmpeg:868");
   }

   return true;
}

// All paths in this that fail must report their error to the user.
bool FFmpegExporter::EncodeAudioFrame(int16_t *pFrame, size_t numSamples)
{
   const auto frameSize = numSamples * sizeof(int16_t) *  mChannels;
   int nBytesToWrite = 0;
   uint8_t *pRawSamples = nullptr;
   int nAudioFrameSizeOut = mDefaultFrameSize * mEncAudioCodecCtx->GetChannels() * sizeof(int16_t);
   int ret;

   nBytesToWrite = frameSize;
   pRawSamples  = (uint8_t*)pFrame;

   // Put the raw audio samples into the FIFO.
   ret = mEncAudioFifo->Write(pRawSamples, nBytesToWrite);

   if (ret != nBytesToWrite) {
      throw ExportErrorException("FFmpeg:913");
   }

   if (nAudioFrameSizeOut > mEncAudioFifoOutBufSize) {
      throw ExportException(_("FFmpeg : ERROR - nAudioFrameSizeOut too large."));
   }

   // Read raw audio samples out of the FIFO in nAudioFrameSizeOut byte-sized groups to encode.
   while (mEncAudioFifo->GetAvailable() >= nAudioFrameSizeOut)
   {
      mEncAudioFifo->Read(
         mEncAudioFifoOutBuf.data(), nAudioFrameSizeOut);

      std::unique_ptr<AVPacketWrapper> pkt = mFFmpeg->CreateAVPacketWrapper();

      ret = EncodeAudio(*pkt,                       // out
         mEncAudioFifoOutBuf.data(), // in
         mDefaultFrameSize);

      if (ret < 0)
         return false;
   }
   return true;
}

FFmpegExportProcessor::FFmpegExportProcessor(std::shared_ptr<FFmpegFunctions> ffmpeg, int subformat )
   : mFFmpeg(std::move(ffmpeg))
{
   context.subformat = subformat;
}

bool FFmpegExportProcessor::Initialize(AudacityProject& project,
   const Parameters& parameters,
   const wxFileNameWrapper& fName,
   double t0, double t1, bool selectionOnly,
   double sampleRate, unsigned channels,
   MixerOptions::Downmix* mixerSpec,
   const Tags* metadata)
{
   context.t0 = t0;
   context.t1 = t1;

   if (!FFmpegFunctions::Load())
   {
      throw ExportException(_("Properly configured FFmpeg is required to proceed.\nYou can configure it at Preferences > Libraries."));
   }
   // subformat index may not correspond directly to fmts[] index, convert it
   const auto adjustedFormatIndex = AdjustFormatIndex(context.subformat);
   if (channels > ExportFFmpegOptions::fmts[adjustedFormatIndex].maxchannels)
   {
      throw ExportException(XO("Attempted to export %d channels, but maximum number of channels for selected output format is %d")
         .Format(
            channels,
            ExportFFmpegOptions::fmts[adjustedFormatIndex].maxchannels )
         .Translation());
   }

   bool ret = true;

   if (adjustedFormatIndex >= FMT_LAST) {
      // TODO: more precise message
      throw ExportErrorException("FFmpeg:996");
   }

   wxString shortname(ExportFFmpegOptions::fmts[adjustedFormatIndex].shortname);
   if (adjustedFormatIndex == FMT_OTHER)
      shortname = ExportPluginHelpers::GetParameterValue<std::string>(parameters, FEFormatID, "matroska");

   context.exporter = std::make_unique<FFmpegExporter>(mFFmpeg, fName, channels, adjustedFormatIndex);

   ret = context.exporter->Init(shortname.mb_str(), &project, static_cast<int>(sampleRate), metadata, parameters);

   if (!ret) {
      // TODO: more precise message
      throw ExportErrorException("FFmpeg:1008");
   }

   context.mixer =
      context.exporter->CreateMixer(project, selectionOnly, t0, t1, mixerSpec);

   context.status = selectionOnly
         ? XO("Exporting selected audio as %s")
              .Format( ExportFFmpegOptions::fmts[adjustedFormatIndex].description )
         : XO("Exporting the audio as %s")
              .Format( ExportFFmpegOptions::fmts[adjustedFormatIndex].description );

   return true;
}

ExportResult FFmpegExportProcessor::Process(ExportProcessorDelegate& delegate)
{
   delegate.SetStatusString(context.status);
   auto exportResult = ExportResult::Success;
   {
      while (exportResult == ExportResult::Success) {
         auto pcmNumSamples = context.mixer->Process();
         if (pcmNumSamples == 0)
            break;

         short *pcmBuffer = (short *)context.mixer->GetBuffer();

         if (!context.exporter->EncodeAudioFrame(pcmBuffer, pcmNumSamples))
            // All errors should already have been reported.
            return ExportResult::Error;

         if(exportResult == ExportResult::Success)
            exportResult = ExportPluginHelpers::UpdateProgress(
               delegate, *context.mixer, context.t0, context.t1);
      }
   }

   if ( exportResult != ExportResult::Cancelled )
      if ( !context.exporter->Finalize() ) // Finalize makes its own messages
         return ExportResult::Error;
   return exportResult;
}


void AddStringTagUTF8(char field[], int size, wxString value)
{
      memset(field,0,size);
      memcpy(field,value.ToUTF8(),(int)strlen(value.ToUTF8()) > size -1 ? size -1 : strlen(value.ToUTF8()));
}

void AddStringTagANSI(char field[], int size, wxString value)
{
      memset(field,0,size);
      memcpy(field,value.mb_str(),(int)strlen(value.mb_str()) > size -1 ? size -1 : strlen(value.mb_str()));
}

bool FFmpegExporter::AddTags(const Tags *tags)
{
   if (tags == NULL)
   {
      return false;
   }

   SetMetadata(tags, "album", TAG_ALBUM);
   SetMetadata(tags, "comment", TAG_COMMENTS);
   SetMetadata(tags, "genre", TAG_GENRE);
   SetMetadata(tags, "title", TAG_TITLE);
   SetMetadata(tags, "track", TAG_TRACK);

   // Bug 2564: Add m4a tags
   if (mEncFormatDesc->GetAudioCodec() == mFFmpeg->GetAVCodecID(AUDACITY_AV_CODEC_ID_AAC))
   {
      SetMetadata(tags, "artist", TAG_ARTIST);
      SetMetadata(tags, "date", TAG_YEAR);
   }
   else
   {
      SetMetadata(tags, "author", TAG_ARTIST);
      SetMetadata(tags, "year", TAG_YEAR);
   }

   return true;
}

void FFmpegExporter::SetMetadata(const Tags *tags, const char *name, const wxChar *tag)
{
   if (tags->HasTag(tag))
   {
      wxString value = tags->GetTag(tag);

      AVDictionaryWrapper metadata = mEncFormatCtx->GetMetadata();

      metadata.Set(name, mSupportsUTF8 ? value : value.mb_str(), 0);
      mEncFormatCtx->SetMetadata(metadata);
   }
}


//----------------------------------------------------------------------------
// AskResample dialog
//----------------------------------------------------------------------------

int FFmpegExporter::AskResample(int bitrate, int rate, int lowrate, int highrate, const int *sampRates)
{
#if defined(FFMPEG_AUTO_RESAMPLE)
   std::vector<int> rates;

   for (int i = 0; sampRates[i]; ++i)
   {
      rates.push_back(sampRates[i]);
   }

   std::sort(rates.begin(), rates.end());

   int bestRate = 0;
   for (auto i : rates)
   {
      bestRate = i;
      if (i > rate)
      {
         break;
      }
   }

   return bestRate;
#else
   wxDialogWrapper d(nullptr, wxID_ANY, XO("Invalid sample rate"));
   d.SetName();
   wxChoice *choice;
   ShuttleGui S(&d, eIsCreating);

   int selected = -1;

   S.StartVerticalLay();
   {
      S.SetBorder(10);
      S.StartStatic(XO("Resample"));
      {
         S.StartHorizontalLay(wxALIGN_CENTER, false);
         {
            S.AddTitle(
               (bitrate == 0
                  ? XO(
"The project sample rate (%d) is not supported by the current output\nfile format. ")
                       .Format( rate )
                  : XO(
"The project sample rate (%d) and bit rate (%d kbps) combination is not\nsupported by the current output file format. ")
                       .Format( rate, bitrate/1000))
               + XO("You may resample to one of the rates below.")
            );
         }
         S.EndHorizontalLay();

         S.StartHorizontalLay(wxALIGN_CENTER, false);
         {
            choice = S.AddChoice(XO("Sample Rates"),
               [&]{
                  TranslatableStrings choices;
                  for (int i = 0; sampRates[i] > 0; i++)
                  {
                     int label = sampRates[i];
                     if ((!lowrate || label >= lowrate) && (!highrate || label <= highrate))
                     {
                        wxString name = wxString::Format(wxT("%d"),label);
                        choices.push_back( Verbatim( name ) );
                        if (label <= rate)
                           selected = i;
                     }
                  }
                  return choices;
               }(),
               std::max( 0, selected )
            );
         }
         S.EndHorizontalLay();
      }
      S.EndStatic();

      S.AddStandardButtons();
   }
   S.EndVerticalLay();

   d.Layout();
   d.Fit();
   d.SetMinSize(d.GetSize());
   d.Center();

   if (d.ShowModal() == wxID_CANCEL) {
      return 0;
   }

   return wxAtoi(choice->GetStringSelection());
#endif
}

static ExportPluginRegistry::RegisteredPlugin sRegisteredPlugin{ "FFmpeg",
   []{ return std::make_unique< ExportFFmpeg >(); }
};