libopusenc 0.2.1

High-level API for encoding Ogg Opus files
Documentation
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
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
//!
//! # Library
//!
//! This library is a safe Rust wrapper around [libopusenc](https://opus-codec.org/docs/libopusenc_api-0.2/index.html),
//! which provides a convenient high-level API for encoding audio data into the Opus format using
//! the reference codec implementation.
//!
//! # Overview
//!
//! Opus is a totally open, royalty-free, highly versatile audio codec. Opus is unmatched
//! for interactive speech and music transmission over the Internet, but is also intended
//! for storage and streaming applications. It is standardized by the Internet Engineering
//! Task Force (IETF) as [RFC 6716](https://opus-codec.org/) which incorporated technology
//! from Skype’s SILK codec and Xiph.Org’s CELT codec.
//!
//! # Technology
//!
//! Opus can handle a wide range of audio applications, including Voice over IP,
//! videoconferencing, in-game chat, and even remote live music performances. It can scale
//! from low bitrate narrowband speech to very high quality stereo music. Supported features are:
//!
//! * Bitrates from 6 kb/s to 510 kb/s
//! * Sampling rates from 8 kHz (narrowband) to 48 kHz (fullband)
//! * Frame sizes from 2.5 ms to 60 ms
//! * Support for both constant bitrate (CBR) and variable bitrate (VBR)
//! * Audio bandwidth from narrowband to fullband
//! * Support for speech and music
//! * Support for mono and stereo
//! * Support for up to 255 channels (multistream frames)
//! * Dynamically adjustable bitrate, audio bandwidth, and frame size
//! * Good loss robustness and packet loss concealment (PLC)
//! * Floating point and fixed-point implementation
//!
//! You can read the full specification, including the reference implementation, in
//! [RFC 6716](https://opus-codec.org/).
//!
//! # Usage
//!
//! To use this library, you will need to add it as a dependency in your `Cargo.toml` file:
//! ```toml
//! [dependencies]
//! libopusenc = "0.2"
//! ```
//!
//! Once you have added the dependency, you can start using the library in your Rust code.
//! Here's a simple example of how to create an Opus encoder, set some parameters, and encode audio data:
//! ```rust
//! use libopusenc::{OpusEncoder, OpusEncError, OpusEncComments, OpusEncBandwidth};
//! use libopusenc::{OpusEncApplication, OpusEncBitrate, OpusEncSampleRate, OpusEncChannelMapping};
//! use std::io::Write; // Import the Write trait to write to a file
//!
//! fn main() -> Result<(), OpusEncError> {
//!    // Specify a buffer containing the input audio data
//!    let input_data: Vec<i16> = vec![0; 96000]; // Example input buffer (1s of stereo audio at 48 kHz)
//!
//!    // Create a new comments structure to hold metadata for the Opus file
//!    // This is optional, but allows you to add metadata like title, artist, etc. to the Opus file
//!    let mut comments = OpusEncComments::create()?;
//!    comments.add("TITLE", "My Opus Track")? // Add a title to the comments
//!            .add("ARTIST", "My Artist")?  // Add an artist name
//!            .add("ALBUM", "My Album")?; // Add an album name
//!
//!    // Create a new Opus encoder for stereo input audio with a sample rate of 48 kHz
//!    let mut encoder = OpusEncoder::create_file("target/out.opus", &mut comments, OpusEncSampleRate::Hz48000, 2, OpusEncChannelMapping::MonoStereo)?;
//!
//!    // Set the encoding parameters
//!    encoder.set_vbr(true)?  // Enable variable bitrate (VBR) encoding
//!           .set_complexity(10)? // Set the complexity level (0-10, higher means more CPU usage)
//!           .set_bandwidth(OpusEncBandwidth::SuperWideband12kHz)?  // Set the output bandwidth to 12 kHz
//!           .set_application(OpusEncApplication::Audio)?  // Set the application type to audio
//!           .set_bitrate(OpusEncBitrate::Explicit(24000))?; // Set the target bitrate to 24 kb/s
//!
//!    // Encode the audio data in the input buffer into single-channel output
//!    if let Err(err) = encoder.write(&input_data, 1) {
//!       println!("Failed to encode audio: {}", err);
//!       return Err(err); // Return the error if encoding failed
//!    }
//!    println!("Successfully wrote Opus data to the output file");
//!    Ok(())
//! }
//! ```
//!
//! The same data can be encoded using callbacks instead of writing directly to a file. This allows you to
//! handle the encoded data in a custom way, such as sending it over a network or storing it into memory.
//! Here's an example of how to encode using callbacks:
//!
//! ```rust
//! use libopusenc::{OpusEncoder, OpusEncError, OpusEncComments, OpusEncBandwidth};
//! use libopusenc::{OpusEncApplication, OpusEncBitrate, OpusEncSampleRate, OpusEncChannelMapping};
//! use std::io::Write; // Import the Write trait to write to a file
//!
//! fn write_callback(file: &mut std::fs::File, data: &[u8]) -> bool {
//!    file.write_all(data).expect("Failed to write data to file from within callback");
//!    true
//! }
//! fn close_callback(_file: &mut std::fs::File) -> bool { true }
//!
//! fn main() -> Result<(), OpusEncError> {
//!    // Specify a buffer containing the input audio data
//!    let input_data: Vec<i16> = vec![0; 96000]; // Example input buffer (1s of stereo audio at 48 kHz)
//!
//!    // Create a new output file to write the encoded Opus data
//!    let mut output_file = std::fs::File::create("target/out_cb.opus").expect("Failed to create output file");
//!
//!    // Create a new comments structure to hold metadata for the Opus file
//!    // This is optional, but allows you to add metadata like title, artist, etc. to the Opus file
//!    let mut comments = OpusEncComments::create()?;
//!    comments.add("TITLE", "My Opus Track")? // Add a title to the comments
//!            .add("ARTIST", "My Artist")?  // Add an artist name
//!            .add("ALBUM", "My Album")?; // Add an album name
//!
//!    // Create a new callback-based Opus encoder for stereo input audio with a sample rate of 48 kHz
//!    let mut encoder = OpusEncoder::create_callbacks(write_callback,
//!                                                    close_callback,
//!                                                    Some(&mut output_file),
//!                                                    &mut comments,
//!                                                    OpusEncSampleRate::Hz48000,
//!                                                    2,
//!                                                    OpusEncChannelMapping::MonoStereo)?;
//!
//!    // Set the encoding parameters
//!    encoder.set_vbr(true)?  // Enable variable bitrate (VBR) encoding
//!           .set_complexity(10)? // Set the complexity level (0-10, higher means more CPU usage)
//!           .set_bandwidth(OpusEncBandwidth::SuperWideband12kHz)?  // Set the output bandwidth to 12 kHz
//!           .set_application(OpusEncApplication::Audio)?  // Set the application type to audio
//!           .set_bitrate(OpusEncBitrate::Explicit(24000))?; // Set the target bitrate to 24 kb/s
//!
//!    // Encode the audio data in the input buffer into single-channel output
//!    if let Err(err) = encoder.write(&input_data, 1) {
//!       println!("Failed to encode audio: {}", err);
//!       return Err(err); // Return the error if encoding failed
//!    }
//!    println!("Successfully wrote Opus data to the output file");
//!    Ok(())
//! }
//! ```

#![cfg_attr(not(test), no_std)]

extern crate alloc;

use alloc::{borrow::ToOwned, boxed::Box, ffi::CString, string::String};
use core::{ffi::CStr, fmt};
use libopusenc_static_sys as ope;
use opus_static_sys as opus;

/// Enumerates potential Opus encoding errors.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncError {
  /// A bad or invalid argument was passed to the function.
  BadArg = ope::OPE_BAD_ARG,
  /// An internal library error occurred.
  InternalError = ope::OPE_INTERNAL_ERROR,
  /// An unimplemented feature was requested.
  Unimplemented = ope::OPE_UNIMPLEMENTED,
  /// Memory allocation failed.
  AllocFail = ope::OPE_ALLOC_FAIL,
  /// The specified file could not be opened.
  CannotOpen = ope::OPE_CANNOT_OPEN,
  /// The encoder is too late to write the data.
  TooLate = ope::OPE_TOO_LATE,
  /// The specified picture is invalid.
  InvalidPicture = ope::OPE_INVALID_PICTURE,
  /// The specified icon is invalid.
  InvalidIcon = ope::OPE_INVALID_ICON,
  /// Failed to write data to the file or stream.
  WriteFail = ope::OPE_WRITE_FAIL,
  /// Failed to close an open file or stream.
  CloseFail = ope::OPE_CLOSE_FAIL,
  /// Failed to convert a Rust string to a C string.
  RustStringConversion = 12,
  /// An unknown error occurred.
  Unknown = -1,
}

impl OpusEncError {
  #[must_use]
  pub(crate) fn from_native(error: core::ffi::c_int) -> Self {
    match error {
      -11 => Self::BadArg,
      -13 => Self::InternalError,
      -15 => Self::Unimplemented,
      -17 => Self::AllocFail,
      -30 => Self::CannotOpen,
      -31 => Self::TooLate,
      -32 => Self::InvalidPicture,
      -33 => Self::InvalidIcon,
      -34 => Self::WriteFail,
      -35 => Self::CloseFail,
      _ => Self::Unknown,
    }
  }
}

impl fmt::Display for OpusEncError {
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    unsafe {
      let c_str = CStr::from_ptr(ope::ope_strerror(*self as core::ffi::c_int));
      write!(f, "{}", c_str.to_str().unwrap_or_default())
    }
  }
}

/// Enumerates available Opus encoding bandwidths.
#[allow(clippy::cast_sign_loss)]
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncBandwidth {
  /// Automatic bandwidth selection (the default value).
  Auto = opus::OPUS_AUTO as u32,
  /// Narrowband (4 kHz).
  Narrowband4kHz = opus::OPUS_BANDWIDTH_NARROWBAND,
  /// Mediumband (6 kHz).
  Mediumband6kHz = opus::OPUS_BANDWIDTH_MEDIUMBAND,
  /// Wideband (8 kHz).
  Wideband8kHz = opus::OPUS_BANDWIDTH_WIDEBAND,
  /// Superwideband (12 kHz).
  SuperWideband12kHz = opus::OPUS_BANDWIDTH_SUPERWIDEBAND,
  /// Fullband (20 kHz).
  Fullband20kHz = opus::OPUS_BANDWIDTH_FULLBAND,
}

impl OpusEncBandwidth {
  #[allow(clippy::cast_sign_loss)]
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val as u32 {
      opus::OPUS_BANDWIDTH_NARROWBAND => Self::Narrowband4kHz,
      opus::OPUS_BANDWIDTH_MEDIUMBAND => Self::Mediumband6kHz,
      opus::OPUS_BANDWIDTH_WIDEBAND => Self::Wideband8kHz,
      opus::OPUS_BANDWIDTH_SUPERWIDEBAND => Self::SuperWideband12kHz,
      opus::OPUS_BANDWIDTH_FULLBAND => Self::Fullband20kHz,
      _ => Self::Auto,
    }
  }
}

/// Enumerates target Opus encoding applications.
///
/// This setting is used to optimize the encoder for different types of audio content.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncApplication {
  /// Voice over IP (VoIP) application.
  Voip = opus::OPUS_APPLICATION_VOIP,
  /// Audio application (the default value).
  Audio = opus::OPUS_APPLICATION_AUDIO,
  /// Low latency, low delay application.
  RestrictedLowDelay = opus::OPUS_APPLICATION_RESTRICTED_LOWDELAY,
}

impl OpusEncApplication {
  #[allow(clippy::cast_sign_loss)]
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val as u32 {
      opus::OPUS_APPLICATION_VOIP => Self::Voip,
      opus::OPUS_APPLICATION_RESTRICTED_LOWDELAY => Self::RestrictedLowDelay,
      _ => Self::Audio,
    }
  }
}

/// Enumerates available Opus encoding frame sizes.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncFrameSize {
  /// Automatic frame size selection (the default value).
  MSARG = opus::OPUS_FRAMESIZE_ARG,
  /// 2.5 ms frame size.
  MS2_5 = opus::OPUS_FRAMESIZE_2_5_MS,
  /// 5 ms frame size.
  MS5 = opus::OPUS_FRAMESIZE_5_MS,
  /// 10 ms frame size.
  MS10 = opus::OPUS_FRAMESIZE_10_MS,
  /// 20 ms frame size.
  MS20 = opus::OPUS_FRAMESIZE_20_MS,
  /// 40 ms frame size.
  MS40 = opus::OPUS_FRAMESIZE_40_MS,
  /// 60 ms frame size.
  MS60 = opus::OPUS_FRAMESIZE_60_MS,
  /// 80 ms frame size.
  MS80 = opus::OPUS_FRAMESIZE_80_MS,
  /// 100 ms frame size.
  MS100 = opus::OPUS_FRAMESIZE_100_MS,
  /// 120 ms frame size.
  MS120 = opus::OPUS_FRAMESIZE_120_MS,
}

impl OpusEncFrameSize {
  #[allow(clippy::cast_sign_loss)]
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val as u32 {
      opus::OPUS_FRAMESIZE_2_5_MS => Self::MS2_5,
      opus::OPUS_FRAMESIZE_5_MS => Self::MS5,
      opus::OPUS_FRAMESIZE_10_MS => Self::MS10,
      opus::OPUS_FRAMESIZE_20_MS => Self::MS20,
      opus::OPUS_FRAMESIZE_40_MS => Self::MS40,
      opus::OPUS_FRAMESIZE_60_MS => Self::MS60,
      opus::OPUS_FRAMESIZE_80_MS => Self::MS80,
      opus::OPUS_FRAMESIZE_100_MS => Self::MS100,
      opus::OPUS_FRAMESIZE_120_MS => Self::MS120,
      _ => Self::MSARG,
    }
  }
}

/// Enumerates available forced number of encoding channels.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncForcedChannels {
  /// Automatic channel selection (the default value).
  Auto = opus::OPUS_AUTO,
  /// Forced mono channel.
  Mono = 1,
  /// Forced stereo channels.
  Stereo = 2,
}

impl OpusEncForcedChannels {
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val {
      1 => Self::Mono,
      2 => Self::Stereo,
      _ => Self::Auto,
    }
  }
}

/// Enumerates all Opus Forward Error Correction (FEC) settings.
///
/// This setting is used to enable or disable in-band FEC.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncInbandFec {
  /// In-band FEC disabled (the default value).
  Disabled = 0,
  /// In-band FEC enabled if packet loss rate is sufficiently high.
  EnabledAlwaysSwitch = 1,
  /// In-band FEC enabled, but not necessarily used if audio is music.
  EnabledSometimesSwitch = 2,
}

/// Enumerates Opus prediction settings.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncPrediction {
  /// Prediction enabled (the default value).
  Enabled = 0,
  /// Prediction disabled.
  Disabled = 1,
}

/// Enumerates Opus signal bias settings.
#[allow(clippy::cast_sign_loss)]
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncSignalBias {
  /// Automatic signal bias selection (the default value).
  Auto = opus::OPUS_AUTO as u32,
  /// Bias toward choosing LPC or hybrid modes (voice signals).
  LpcHybrid = opus::OPUS_SIGNAL_VOICE,
  /// Bias toward choosing MDCT modes (music signals).
  MDCT = opus::OPUS_SIGNAL_MUSIC,
}

impl OpusEncSignalBias {
  #[allow(clippy::cast_sign_loss)]
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val as u32 {
      opus::OPUS_SIGNAL_VOICE => Self::LpcHybrid,
      opus::OPUS_SIGNAL_MUSIC => Self::MDCT,
      _ => Self::Auto,
    }
  }
}

/// Enumerates Opus encoding bitrate options.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncBitrate {
  /// Automatic bitrate selection (the default value).
  Auto = opus::OPUS_AUTO,
  /// Maximum allowable bitrate.
  Max = opus::OPUS_BITRATE_MAX,
  /// Explicit bitrate (between 500 and 512,000 bits per second).
  Explicit(u32),
}

impl OpusEncBitrate {
  #[must_use]
  #[allow(clippy::cast_sign_loss)]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val {
      opus::OPUS_AUTO => Self::Auto,
      opus::OPUS_BITRATE_MAX => Self::Max,
      val => Self::Explicit(val as u32),
    }
  }

  #[must_use]
  #[allow(clippy::cast_possible_wrap)]
  pub(crate) fn to_native(self) -> core::ffi::c_int {
    match self {
      Self::Auto => opus::OPUS_AUTO,
      Self::Max => opus::OPUS_BITRATE_MAX,
      Self::Explicit(val) => val as core::ffi::c_int,
    }
  }
}

/// Enumerates available Opus encoding requests.
///
/// This setting is used to control various aspects of the encoder's behavior.
/// The requests are used to set or get specific parameters of the encoder.
#[repr(u32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncRequest {
  /// Resets the codec to be equivalent to a freshly initialized state.
  ///
  /// This should be used when switching streams in order to prevent back-to-back
  /// encoding from giving different results from one-at-a-time encoding.
  ResetState = opus::OPUS_RESET_STATE,
  /// Gets the final state of the codec's entropy coder, used for testing purposes.
  GetFinalRange = opus::OPUS_GET_FINAL_RANGE_REQUEST,
  /// Sets the encoder's bandpass to a specific value.
  ///
  /// This prevents the encoder from automatically selecting the bandpass based on
  /// the available bitrate.
  ///
  /// If the application knows the bandpass of the input audio it is providing, it
  /// should normally use [`OpusEncRequest::SetMaxBandwidth`] instead, which still
  /// gives the encoder the freedom to reduce the bandpass when the bitrate becomes
  /// too low, for better overall quality.
  SetBandwidth = opus::OPUS_SET_BANDWIDTH_REQUEST,
  /// Gets the encoder's configured bandpass or the decoder's last bandpass.
  GetBandwidth = opus::OPUS_GET_BANDWIDTH_REQUEST,
  /// Gets the sample rate the encoder or decoder was initialized with.
  GetSampleRate = opus::OPUS_GET_SAMPLE_RATE_REQUEST,
  /// Disables the use of phase inversion for intensity stereo, improving the quality
  /// of mono downmixes, but slightly reducing normal stereo quality.
  SetPhaseInversionDisabled = opus::OPUS_SET_PHASE_INVERSION_DISABLED_REQUEST,
  /// Gets the encoder's configured phase inversion status.
  GetPhaseInversionDisabled = opus::OPUS_GET_PHASE_INVERSION_DISABLED_REQUEST,
  /// Gets the DTX state of the encoder.
  ///
  /// Returns whether the last encoded frame was either a comfort noise update during
  /// DTX or not encoded because of DTX.
  GetInDtx = opus::OPUS_GET_IN_DTX_REQUEST,
  /// Configures the encoder's computational complexity.
  ///
  /// The supported range is 0-10 inclusive, with 10 representing the highest complexity.
  SetComplexity = opus::OPUS_SET_COMPLEXITY_REQUEST,
  /// Gets the encoder's computational complexity configuration, ranging from 0-10 inclusive.
  GetComplexity = opus::OPUS_GET_COMPLEXITY_REQUEST,
  /// Configures the birate of the encoder.
  ///
  /// Rates from 500-512,000 bits per second are meaningful, as well as the special
  /// values [`OpusEncBitrate::Auto`] and [`OpusEncBitrate::Max`]. The value
  /// [`OpusEncBitrate::Max`] can be used to cause the codec to use as much rate
  /// as it can, which is useful for controlling the rate by adjusting the output
  /// buffer size.
  SetBitrate = opus::OPUS_SET_BITRATE_REQUEST,
  /// Gets the encoder's bitrate configuration.
  ///
  /// The default configuration is based on the number of channels and the input
  /// sampling rate.
  GetBitrate = opus::OPUS_GET_BITRATE_REQUEST,
  /// Enables or disables variable bitrate (VBR) encoding.
  ///
  /// The configured bitrate is still used as a target, but the encoder is free to
  /// use a lower bitrate if the input signal does not require it.
  SetVbr = opus::OPUS_SET_VBR_REQUEST,
  /// Determines whether variable bitrate (VBR) encoding is enabled or disabled.
  GetVbr = opus::OPUS_GET_VBR_REQUEST,
  /// Enables or disables constrained variable bitrate (VBR) encoding.
  ///
  /// This setting is ignored when the encoder is in constant bitrate (CBR) mode.
  SetVbrConstraint = opus::OPUS_SET_VBR_CONSTRAINT_REQUEST,
  /// Determines whether constrained variable bitrate (VBR) is enabled or disabled.
  GetVbrConstraint = opus::OPUS_GET_VBR_CONSTRAINT_REQUEST,
  /// Configures mono/stereo enforcing in the encoder.
  ///
  /// This can force the encoder to produce packets encoded as either mono or stereo,
  /// regardless of the number of channels in the input audio. This is useful when the caller
  /// knows that the input signal is currently a mono source embedded in a stereo stream.
  SetForceChannels = opus::OPUS_SET_FORCE_CHANNELS_REQUEST,
  /// Gets the encoder's configured forced number of channels.
  GetForceChannels = opus::OPUS_GET_FORCE_CHANNELS_REQUEST,
  /// Configures the maximum bandpass that the encoder will select automatically, requiring
  /// a variant of [`OpusEncBandwidth`].
  ///
  /// Applications should normally use this instead of [`OpusEncRequest::SetBandwidth`]
  /// to allow the encoder to select the bandpass based on the available bitrate.
  SetMaxBandwidth = opus::OPUS_SET_MAX_BANDWIDTH_REQUEST,
  /// Gets the encoder's configured maximum allowed bandpass.
  ///
  /// Returns a variant of [`OpusEncBandwidth`].
  GetMaxBandwidth = opus::OPUS_GET_MAX_BANDWIDTH_REQUEST,
  /// Configures the type of signal being encoded, requiring a variant of
  /// [`OpusEncSignalBias`], where [`OpusEncSignalBias::LpcHybrid`] indicates a voice-like
  /// signal, and [`OpusEncSignalBias::MDCT`] indicates a music-like signal.
  ///
  /// This is a hint which helps the encoder's mode selection.
  SetSignal = opus::OPUS_SET_SIGNAL_REQUEST,
  /// Gets the encoder's configured signal type.
  ///
  /// Returns a variant of [`OpusEncSignalBias`], where [`OpusEncSignalBias::LpcHybrid`]
  /// indicates a voice-like signal, and [`OpusEncSignalBias::MDCT`] indicates a music-like
  /// signal.
  GetSignal = opus::OPUS_GET_SIGNAL_REQUEST,
  /// Configures the encoder's intended application.
  ///
  /// Requires a variant of [`OpusEncApplication`].
  SetApplication = opus::OPUS_SET_APPLICATION_REQUEST,
  /// Gets the encoder's configured application.
  ///
  /// Returns a variant of [`OpusEncApplication`].
  GetApplication = opus::OPUS_GET_APPLICATION_REQUEST,
  /// Gets the total number of delay samples added by the entire codec.
  ///
  /// This can be queried by the encoder, and then the provided number of samples can
  /// be skipped from the start of the decoder's output to provide time-aligned input
  /// and output. From the perspective of a decoding application, the real audio data
  /// begins this many samples late.
  ///
  /// The decoder contribution to this delay is identical for all decoders, but the
  /// encoder portion may vary from implementation to implementation, version to version,
  /// or even depend on the encoder's initial configuration. Applications needing
  /// delay compensation should call this CTL rather than hard-coding a value.
  GetLookahead = opus::OPUS_GET_LOOKAHEAD_REQUEST,
  /// Configures the encoder's use of in-band Forward Error Correction (FEC), requiring
  /// a variant of [`OpusEncInbandFec`].
  SetInbandFec = opus::OPUS_SET_INBAND_FEC_REQUEST,
  /// Gets the encoder's configured in-band Forward Error Correction (FEC) state.
  ///
  /// Returns a variant of [`OpusEncInbandFec`].
  GetInbandFec = opus::OPUS_GET_INBAND_FEC_REQUEST,
  /// Configures the encoder's expected packet loss percentage, in the range 0-100.
  ///
  /// Higher values trigger progressively more loss-resistant behavior in the encoder
  /// at the expense of quality at a given bitrate in the absence of packet loss, but
  /// greater quality under loss.
  SetPacketLossPerc = opus::OPUS_SET_PACKET_LOSS_PERC_REQUEST,
  /// Gets the encoder's configured packet loss percentage in the range 0-100.
  GetPacketLossPerc = opus::OPUS_GET_PACKET_LOSS_PERC_REQUEST,
  /// Sets whether Discontinuous Transmission (DTX) is enabled or disabled.
  SetDtx = opus::OPUS_SET_DTX_REQUEST,
  /// Gets whether Discontinuous Transmission (DTX) is enabled or disabled.
  GetDtx = opus::OPUS_GET_DTX_REQUEST,
  /// Configures the depth (bit precision) of the signal being encoded.
  ///
  /// This is a hint which helps the encoder identify silence and near-silence. It
  /// represents the number of significant bits of linear intensity below which the signal
  /// contains ignorable quantization or other noise.
  ///
  /// For example, a bit-depth of 14 would be appropriate for G.711 u-law input. A bit-depth
  /// of 16 would be appropriate for 16-bit linear PCM input.
  SetLsbDepth = opus::OPUS_SET_LSB_DEPTH_REQUEST,
  /// Gets the encoder's configured signal depth (input precision in bits).
  GetLsbDepth = opus::OPUS_GET_LSB_DEPTH_REQUEST,
  /// Configures the encoder's use of variable duration frames.
  ///
  /// When variable duration is enabled, the encoder is free to use a shorter frame size
  /// than the one requested during encoder initialization. It is then the user's
  /// responsibility to verify how much audio was encoded by checking the `ToC` byte
  /// of the encoded packet. The part of the audio that was not encoded needs to be
  /// resent to the encoder for the next call.
  ///
  /// Do not use this option unless you **really** know what you are doing.
  SetExpertFrameDuration = opus::OPUS_SET_EXPERT_FRAME_DURATION_REQUEST,
  /// Gets the encoder's configured use of variable duration frames.
  ///
  /// Returns a variant of [`OpusEncFrameSize`].
  GetExpertFrameDuration = opus::OPUS_GET_EXPERT_FRAME_DURATION_REQUEST,
  /// Disables almost all use of prediction if set to `1`, making frames almost completely
  /// independent. This reduces quality.
  SetPredictionDisabled = opus::OPUS_SET_PREDICTION_DISABLED_REQUEST,
  /// Gets the encoder's configured prediction status, where `0` means `enabled`.
  GetPredictionDisabled = opus::OPUS_GET_PREDICTION_DISABLED_REQUEST,
  /// Enables Deep Redundancy (DRED) with any non-zero value, specifying the maximum
  /// number of 10-ms redundant frames to be used.
  SetDredDuration = opus::OPUS_SET_DRED_DURATION_REQUEST,
  /// Gets the encoder's configured Deep Redundancy (DRED) maximum number of frames.
  GetDredDuration = opus::OPUS_GET_DRED_DURATION_REQUEST,
  /// Provides external DNN weights from a binary object (only when explicitly built
  /// without the weights).
  SetDnnBlob = opus::OPUS_SET_DNN_BLOB_REQUEST,
  /// Configures the encoder's delay due to use of a DNN-based denoiser.
  SetDecisionDelay = ope::OPE_SET_DECISION_DELAY_REQUEST,
  /// Gets the encoder's configured delay due to use of a DNN-based denoiser.
  GetDecisionDelay = ope::OPE_GET_DECISION_DELAY_REQUEST,
  /// Configures the encoder's delay due to Ogg multiplexing.
  SetMuxingDelay = ope::OPE_SET_MUXING_DELAY_REQUEST,
  /// Gets the encoder's configured delay due to Ogg multiplexing.
  GetMuxingDelay = ope::OPE_GET_MUXING_DELAY_REQUEST,
  /// Configures the number of extra bytes to reserve for comments and metadata (defaults to 512).
  SetCommentPadding = ope::OPE_SET_COMMENT_PADDING_REQUEST,
  /// Gets the encoder's configured number of extra bytes to reserve for comments and metadata.
  GetCommentPadding = ope::OPE_GET_COMMENT_PADDING_REQUEST,
  /// Assigns a serial number to the current stream.
  SetSerialNo = ope::OPE_SET_SERIALNO_REQUEST,
  /// Gets the serial number of the current stream.
  GetSerialNo = ope::OPE_GET_SERIALNO_REQUEST,
  /// Configures the internal callback used when writing a data packet. **DO NOT USE THIS**.
  SetPacketCallback = ope::OPE_SET_PACKET_CALLBACK_REQUEST,
  /// Configures the amount of gain to apply upon playback.
  ///
  /// **0 dB is recommended unless you know what you are doing.**
  SetHeaderGain = ope::OPE_SET_HEADER_GAIN_REQUEST,
  /// Gets the amount of gain to apply upon playback.
  GetHeaderGain = ope::OPE_GET_HEADER_GAIN_REQUEST,
  /// Gets the number of streams in the current OggOpus stream.
  GetNbStreams = ope::OPE_GET_NB_STREAMS_REQUEST,
  /// Gets the number of coupled streams in the current OggOpus stream.
  GetNbCoupledStreams = ope::OPE_GET_NB_COUPLED_STREAMS_REQUEST,
}

/// Enumerates available embedded metadata picture types.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncPictureType {
  /// Default picture type, used when no specific type is provided.
  Default = -1,
  /// Indicates that the picture type is not specified or is unknown.
  Other = 0,
  /// PNG 32x32 pixel file icon.
  PngFileIcon32x32 = 1,
  /// Non-PNG file icon.
  OtherFileIcon = 2,
  /// Album art for the front cover of an album or single.
  FrontCover = 3,
  /// Album art for the back cover of an album or single.
  BackCover = 4,
  /// Leaflet or booklet page, typically used for additional information about the album.
  LeafletPage = 5,
  /// Media label, typically used for the disc or media label of a physical release.
  MediaLabel = 6,
  /// Lead artist or main performer of the audio content.
  LeadArtist = 7,
  /// Indicates the lead artist or main performer of the audio content.
  ArtistPerformer = 8,
  /// Conductor of the band or symphony responsible for performance of the audio content.
  Conductor = 9,
  /// Band or orchestra name responsible for performing the audio content.
  BandOrchestra = 10,
  /// Composer of the music or composition.
  Composer = 11,
  /// Lyricist or author of the lyrics of the composition.
  Lyricist = 12,
  /// Location where the recording was made.
  RecordingLocation = 13,
  /// Media content taken during recording of the audio.
  DuringRecording = 14,
  /// Media content taken during performance of the audio.
  DuringPerformance = 15,
  /// Movie screen capture or screenshot from a movie related to the audio content.
  MovieScreenCap = 16,
  /// Bright colored fish, typically used for decorative purposes or as a fun representation.
  BrightColoredFish = 17,
  /// Illustration or artwork related to the audio content.
  Illustration = 18,
  /// Artist logotype, typically used for branding or promotional purposes related to the artist.
  ArtistLogotype = 19,
  /// Publisher logotype, typically used for branding or promotional purposes related to the publisher.
  PublisherLogotype = 20,
}

/// Enumerates Opus encoding channel mapping modes.
///
/// This setting is used to control how the encoder maps channels to the output stream.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncChannelMapping {
  MonoStereo = 0,
  Surround = 1,
}

/// Enumerates available Opus encoding sample rates.
#[repr(i32)]
#[derive(Debug, Copy, Clone)]
pub enum OpusEncSampleRate {
  /// 48 kHz audio sample rate.
  Hz48000 = 48000,
  /// 24 kHz audio sample rate.
  Hz24000 = 24000,
  /// 16 kHz audio sample rate.
  Hz16000 = 16000,
  /// 12 kHz audio sample rate.
  Hz12000 = 12000,
  /// 8 kHz audio sample rate.
  Hz8000 = 8000,
}

impl OpusEncSampleRate {
  #[must_use]
  pub(crate) fn from_native(val: core::ffi::c_int) -> Self {
    match val {
      24000 => Self::Hz24000,
      16000 => Self::Hz16000,
      12000 => Self::Hz12000,
      8000 => Self::Hz8000,
      _ => Self::Hz48000,
    }
  }
}

/// Callback function definition for writing encoded data to an output file or structure.
///
/// # Arguments
///
/// * `user_data` - User-defined data passed to the callback (such as a file pointer)
/// * `ogg_opus_data` - OggOpus data buffer to be written to the output
///
/// # Returns
///
/// * `true` = Writing successful
/// * `false` = Writing failed
pub type OpeWriteFunc<T> = fn(user_data: &mut T, ogg_opus_data: &[u8]) -> bool;

/// Callback function definition for closing an output file or structure.
///
/// # Arguments
///
/// * `user_data` - User-defined data passed to the callback (such as a file pointer)
///
/// # Returns
///
/// * `true` = Closing successful
/// * `false` = Closing failed
pub type OpeCloseFunc<T> = fn(user_data: &mut T) -> bool;

/// Returns a String representing the library version being used.
///
/// # Returns
///
/// A string describing the library version
#[must_use]
pub fn get_version_string() -> String {
  unsafe {
    let c_str = CStr::from_ptr(ope::ope_get_version_string());
    c_str.to_str().unwrap_or_default().to_owned()
  }
}

/// Returns the ABI version used by this library.
///
/// This can be used to check for features at runtime.
///
/// # Returns
///
/// An integer representing the library ABI version
#[must_use]
pub fn get_abi_version() -> i32 {
  unsafe { ope::ope_get_abi_version() }
}

/// Encapsulates all metadata associated with an OggOpus stream.
pub struct OpusEncComments {
  ptr: *mut ope::OggOpusComments,
}

impl Drop for OpusEncComments {
  fn drop(&mut self) {
    unsafe {
      if !self.ptr.is_null() {
        ope::ope_comments_destroy(self.ptr);
      }
    }
  }
}

impl OpusEncComments {
  /// Creates a new instance of [`OpusEncComments`] to store audio metadata.
  ///
  /// # Returns
  ///
  /// A new instance of [`OpusEncComments`] if successful, or an [`OpusEncError`]
  /// if creation failed.
  /// 
  /// # Errors
  /// 
  /// If the creation of the comments structure fails, it will return an
  /// [`OpusEncError::AllocFail`].
  pub fn create() -> Result<Self, OpusEncError> {
    let ptr = unsafe { ope::ope_comments_create() };
    if ptr.is_null() {
      Err(OpusEncError::AllocFail)
    } else {
      Ok(Self { ptr })
    }
  }

  /// Adds a tag and value pair to the metadata.
  ///
  /// The tag and value can be any string, e.g., `"ARTIST"` and `"The Beatles"`.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEncComments`] if successful,
  /// or an error if the addition failed.
  ///
  /// # Errors
  ///
  /// A [`OpusEncError::RustStringConversion`] will be returned if the conversion
  /// of the tag or value to a C string fails.
  ///
  /// Any potential [`OpusEncError`] may be returned if the call to the
  /// underlying native function fails.
  pub fn add(&mut self, tag: &str, val: &str) -> Result<&mut Self, OpusEncError> {
    let tag = CString::new(tag).map_err(|_| OpusEncError::RustStringConversion)?;
    let val = CString::new(val).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      match ope::ope_comments_add(self.ptr, tag.as_ptr(), val.as_ptr()) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Adds a string containing a tag-value pair to the metadata.
  ///
  /// The tag-value pair can be any set of strings, e.g., `"ARTIST=The Beatles"`.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEncComments`] if successful,
  /// or an error if the addition failed.
  ///
  /// # Errors
  ///
  /// A [`OpusEncError::RustStringConversion`] will be returned if the conversion
  /// of the tag-value pair to a C string fails.
  ///
  /// Any potential [`OpusEncError`] may be returned if the call to the
  /// underlying native function fails.
  pub fn add_string(&mut self, tag_and_val: &str) -> Result<&mut Self, OpusEncError> {
    let tag_and_val = CString::new(tag_and_val).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      match ope::ope_comments_add_string(self.ptr, tag_and_val.as_ptr()) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Adds a picture with the given content, type, and description to the metadata.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEncComments`] if successful,
  /// or an error if the addition failed.
  ///
  /// # Errors
  ///
  /// A [`OpusEncError::RustStringConversion`] will be returned if the conversion
  /// of the description to a C string fails.
  ///
  /// Any potential [`OpusEncError`] may be returned if the call to the
  /// underlying native function fails.
  pub fn add_picture(
    &mut self,
    filename: &str,
    picture_type: OpusEncPictureType,
    description: &str,
  ) -> Result<&mut Self, OpusEncError> {
    let filename = CString::new(filename).map_err(|_| OpusEncError::RustStringConversion)?;
    let description = CString::new(description).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      match ope::ope_comments_add_picture(
        self.ptr,
        filename.as_ptr(),
        picture_type as core::ffi::c_int,
        description.as_ptr(),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Adds a picture with the given content, type, and description to the metadata.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEncComments`] if successful,
  /// or an error if the addition failed.
  ///
  /// # Errors
  ///
  /// A [`OpusEncError::RustStringConversion`] will be returned if the conversion
  /// of the description to a C string fails.
  ///
  /// Any potential [`OpusEncError`] may be returned if the call to the
  /// underlying native function fails.
  pub fn add_picture_from_memory(
    &mut self,
    data: &[u8],
    picture_type: OpusEncPictureType,
    description: &str,
  ) -> Result<&mut Self, OpusEncError> {
    let description = CString::new(description).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      match ope::ope_comments_add_picture_from_memory(
        self.ptr,
        data.as_ptr().cast(),
        data.len(),
        picture_type as core::ffi::c_int,
        description.as_ptr(),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }
}

/// Encapsulates the real-time internal state of an OggOpus encoder.
pub struct OpusEnc<'a, T> {
  ptr: *mut ope::OggOpusEnc,
  write_cb: Option<OpeWriteFunc<T>>,
  close_cb: Option<OpeCloseFunc<T>>,
  cb_user_data: Option<&'a mut T>,
}

impl<T> Drop for OpusEnc<'_, T> {
  fn drop(&mut self) {
    unsafe {
      if !self.ptr.is_null() {
        ope::ope_encoder_drain(self.ptr);
        ope::ope_encoder_destroy(self.ptr);
      }
    }
  }
}

impl<'a, T> OpusEnc<'a, T> {
  #[allow(clippy::cast_sign_loss)]
  unsafe extern "C" fn write_cb(user_data: *mut core::ffi::c_void, data: *const u8, len: i32) -> i32 {
    unsafe {
      let enc = &mut *(user_data.cast::<Self>());
      if let Some(callback) = enc.write_cb {
        let ogg_opus_data = if data.is_null() {
          &[]
        } else {
          alloc::slice::from_raw_parts(data, len as usize)
        };
        if let Some(cb_user_data) = &mut enc.cb_user_data {
          i32::from(!callback(cb_user_data, ogg_opus_data))
        } else {
          1
        }
      } else {
        1
      }
    }
  }

  unsafe extern "C" fn close_cb(user_data: *mut core::ffi::c_void) -> i32 {
    unsafe {
      let enc = &mut *(user_data.cast::<Self>());
      if let Some(callback) = enc.close_cb {
        if let Some(cb_user_data) = &mut enc.cb_user_data {
          i32::from(!callback(cb_user_data))
        } else {
          1
        }
      } else {
        1
      }
    }
  }

  /// Adds/encodes any number of float samples to the audio stream.
  ///
  /// # Arguments
  ///
  /// * `pcm` - Floating-point PCM values in the +/-1 range (interleaved if multiple channels)
  /// * `num_channels` - Number of channels
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
  pub fn write_float(&mut self, pcm: &[f32], num_channels: usize) -> Result<&mut Self, OpusEncError> {
    let samples_per_channel = (pcm.len() / num_channels) as core::ffi::c_int;
    unsafe {
      match ope::ope_encoder_write_float(self.ptr, pcm.as_ptr(), samples_per_channel) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Adds/encodes any number of 16-bit linear samples to the audio stream.
  ///
  /// # Arguments
  ///
  /// * `pcm` - 16-bit PCM values in the \[-32768, 32767\] range (interleaved if multiple channels)
  /// * `num_channels` - Number of channels
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
  pub fn write(&mut self, pcm: &[i16], num_channels: usize) -> Result<&mut Self, OpusEncError> {
    let samples_per_channel = (pcm.len() / num_channels) as core::ffi::c_int;
    unsafe {
      match ope::ope_encoder_write(self.ptr, pcm.as_ptr(), samples_per_channel) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the next page from the audio stream.
  ///
  /// Only use this function if the encoder was created using [`OpusEncoder::create_pull()`](OpusEncoder::create_pull).
  ///
  /// # Arguments
  ///
  /// * `flush` - Forces a flush of the page (if any data avaiable)
  ///
  /// # Returns
  ///
  /// A data slice containing the next available encoded page if successful,
  /// or `None` if no more pages are available.
  #[allow(clippy::cast_sign_loss)]
  #[must_use]
  pub fn get_page(&mut self, flush: bool) -> Option<&[u8]> {
    let mut page_size: ope::opus_int32 = 0;
    let mut page_ptr: *mut core::ffi::c_uchar = core::ptr::null_mut();
    unsafe {
      if ope::ope_encoder_get_page(self.ptr, &mut page_ptr, &mut page_size, core::ffi::c_int::from(flush)) == 1 {
        Some(core::slice::from_raw_parts(page_ptr, page_size as usize))
      } else {
        None
      }
    }
  }

  /// Finalizes the audio stream, but does not shut down the encoder.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn drain(&mut self) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_drain(self.ptr) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Ends the current audio stream and creates a new stream within the same file.
  ///
  /// # Arguments
  ///
  /// * `comments` - Comments and metadata to associate with the new stream
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn chain_current(&mut self, comments: &mut OpusEncComments) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_chain_current(self.ptr, comments.ptr) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Ends the current audio stream and creates a new file.
  ///
  /// # Arguments
  ///
  /// * `path` - Path where to create the new file
  /// * `comments` - Comments and metadata to associate with the new stream
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn continue_new_file(&mut self, path: &str, comments: &mut OpusEncComments) -> Result<&mut Self, OpusEncError> {
    let path = CString::new(path).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      match ope::ope_encoder_continue_new_file(self.ptr, path.as_ptr(), comments.ptr) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Ends the current audio stream and creates a new callback-based encoding structure.
  ///
  /// # Arguments
  ///
  /// * `user_data` - Data to pass to the callbacks upon invocation (such as a file pointer)
  /// * `comments` - Comments and metadata to associate with the new stream
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn continue_new_callbacks(
    &mut self,
    user_data: Option<&'a mut T>,
    comments: &mut OpusEncComments,
  ) -> Result<&mut Self, OpusEncError> {
    unsafe {
      self.cb_user_data = user_data;
      match ope::ope_encoder_continue_new_callbacks(self.ptr, core::ptr::from_mut(self).cast(), comments.ptr) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Writes the file header immediately rather than waiting for audio to begin.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn flush_header(&mut self) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_flush_header(self.ptr) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Resets the internal state of the encoder to be the same as if the encoder was
  /// newly created without destroying the encoder itself.
  ///
  /// This should be used when switching streams in order to prevent back-to-back
  /// encoding from giving different results from one-at-a-time encoding.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn reset_state(&mut self) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(self.ptr, OpusEncRequest::ResetState as core::ffi::c_int) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the final state of the codec's entropy coder, used for testing purposes.
  ///
  /// # Returns
  ///
  /// The final state of the codec's entropy coder as a `u32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_final_range(&mut self) -> Result<u32, OpusEncError> {
    let mut final_range: u32 = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetFinalRange as core::ffi::c_int,
        core::ptr::from_mut(&mut final_range),
      ) {
        0 => Ok(final_range),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Sets the encoder's bandpass to a specific value.
  ///
  /// This prevents the encoder from automatically selecting the bandpass based on
  /// the available bitrate.
  ///
  /// If the application knows the bandpass of the input audio it is providing, it
  /// should normally use [`OpusEnc::set_max_bandwidth`] instead, which still
  /// gives the encoder the freedom to reduce the bandpass when the bitrate becomes
  /// too low, for better overall quality.
  ///
  /// # Arguments
  ///
  /// * `bandwidth` - The desired bandpass to set for the encoder, which should be a variant of [`OpusEncBandwidth`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_bandwidth(&mut self, bandwidth: OpusEncBandwidth) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetBandwidth as core::ffi::c_int,
        bandwidth as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured bandpass.
  ///
  /// # Returns
  ///
  /// An [`OpusEncBandwidth`] variant representing the current bandpass setting of the encoder,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_bandwidth(&mut self) -> Result<OpusEncBandwidth, OpusEncError> {
    let mut bandwidth: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetBandwidth as core::ffi::c_int,
        core::ptr::from_mut(&mut bandwidth),
      ) {
        0 => Ok(OpusEncBandwidth::from_native(bandwidth)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the sample rate that the encoder was initialized with.
  ///
  /// # Returns
  ///
  /// An [`OpusEncSampleRate`] variant representing the sample rate of the encoder,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_sample_rate(&mut self) -> Result<OpusEncSampleRate, OpusEncError> {
    let mut rate: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetSampleRate as core::ffi::c_int,
        core::ptr::from_mut(&mut rate),
      ) {
        0 => Ok(OpusEncSampleRate::from_native(rate)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Disables the use of phase inversion for intensity stereo, improving the quality
  /// of mono downmixes, but slightly reducing normal stereo quality.
  ///
  /// # Arguments
  ///
  /// * `disabled` - A boolean value indicating whether to disable phase inversion (`true` to disable, `false` to enable).
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_phase_inversion_disabled(&mut self, disabled: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetPhaseInversionDisabled as core::ffi::c_int,
        core::ffi::c_int::from(disabled),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured phase inversion status.
  ///
  /// # Returns
  ///
  /// `True` if phase inversion is disabled (meaning that the encoder will not use
  /// phase inversion for intensity stereo), and `False` if it is enabled,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_phase_inversion_disabled(&mut self) -> Result<bool, OpusEncError> {
    let mut disabled: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetPhaseInversionDisabled as core::ffi::c_int,
        core::ptr::from_mut(&mut disabled),
      ) {
        0 => Ok(disabled != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the DTX state of the encoder.
  ///
  /// Returns whether the last encoded frame was either a comfort noise update during
  /// DTX or not encoded because of DTX.
  ///
  /// # Returns
  ///
  /// `True` if the last encoded frame was a comfort noise update during DTX or
  /// if the last frame was not encoded because of DTX, or an error if the
  /// operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_in_dtx(&mut self) -> Result<bool, OpusEncError> {
    let mut in_dtx: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetInDtx as core::ffi::c_int,
        core::ptr::from_mut(&mut in_dtx),
      ) {
        0 => Ok(in_dtx != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's computational complexity.
  ///
  /// The supported range is 0-10 inclusive, with 10 representing the highest complexity.
  ///
  /// # Arguments
  ///
  /// * `complexity` - The desired complexity level for the encoder, ranging from 0 to 10.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_complexity(&mut self, complexity: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetComplexity as core::ffi::c_int,
        complexity.clamp(0, 10) as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's computational complexity configuration, ranging from 0-10 inclusive.
  ///
  /// # Returns
  ///
  /// The current complexity setting of the encoder as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_complexity(&mut self) -> Result<i32, OpusEncError> {
    let mut complexity: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetComplexity as core::ffi::c_int,
        core::ptr::from_mut(&mut complexity),
      ) {
        0 => Ok(complexity),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the birate of the encoder.
  ///
  /// Rates from 500-512,000 bits per second are meaningful, as well as the special
  /// values [`OpusEncBitrate::Auto`] and [`OpusEncBitrate::Max`]. The value
  /// [`OpusEncBitrate::Max`] can be used to cause the codec to use as much rate
  /// as it can, which is useful for controlling the rate by adjusting the output
  /// buffer size.
  ///
  /// # Arguments
  ///
  /// * `bitrate` - The desired bitrate for the encoder, which should be a variant of [`OpusEncBitrate`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_bitrate(&mut self, bitrate: OpusEncBitrate) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetBitrate as core::ffi::c_int,
        bitrate.to_native(),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's bitrate configuration.
  ///
  /// The default configuration is based on the number of channels and the input
  /// sampling rate.
  ///
  /// # Returns
  ///
  /// An [`OpusEncBitrate`] variant representing the current bitrate setting of the encoder,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_bitrate(&mut self) -> Result<OpusEncBitrate, OpusEncError> {
    let mut bitrate: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetBitrate as core::ffi::c_int,
        core::ptr::from_mut(&mut bitrate),
      ) {
        0 => Ok(OpusEncBitrate::from_native(bitrate)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Enables or disables variable bitrate (VBR) encoding.
  ///
  /// The configured bitrate is still used as a target, but the encoder is free to
  /// use a lower bitrate if the input signal does not require it.
  ///
  /// # Arguments
  ///
  /// * `vbr` - A boolean value indicating whether to enable (`true`) or disable (`false`) variable bitrate encoding.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_vbr(&mut self, vbr: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetVbr as core::ffi::c_int,
        core::ffi::c_int::from(vbr),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Determines whether variable bitrate (VBR) encoding is enabled or disabled.
  ///
  /// # Returns
  ///
  /// `True` if VBR encoding is enabled, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_vbr(&mut self) -> Result<bool, OpusEncError> {
    let mut vbr: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetVbr as core::ffi::c_int,
        core::ptr::from_mut(&mut vbr),
      ) {
        0 => Ok(vbr != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Enables or disables constrained variable bitrate (VBR) encoding.
  ///
  /// This setting is ignored when the encoder is in constant bitrate (CBR) mode.
  ///
  /// # Arguments
  ///
  /// * `constrainted` - A boolean value indicating whether to enable (`true`) or disable (`false`) constrained VBR encoding.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_vbr_constraint(&mut self, constrained: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetVbrConstraint as core::ffi::c_int,
        core::ffi::c_int::from(constrained),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Determines whether constrained variable bitrate (VBR) is enabled or disabled.
  ///
  /// # Returns
  ///
  /// `True` if constrained VBR is enabled, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_vbr_constraint(&mut self) -> Result<bool, OpusEncError> {
    let mut constrained: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetVbrConstraint as core::ffi::c_int,
        core::ptr::from_mut(&mut constrained),
      ) {
        0 => Ok(constrained != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures mono/stereo enforcing in the encoder.
  ///
  /// This can force the encoder to produce packets encoded as either mono or stereo,
  /// regardless of the number of channels in the input audio. This is useful when the caller
  /// knows that the input signal is currently a mono source embedded in a stereo stream.
  ///
  /// # Arguments
  ///
  /// * `channels` - The desired number of channels for the encoder to enforce, as an [`OpusEncForcedChannels`] variant.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_force_channels(&mut self, channels: OpusEncForcedChannels) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetForceChannels as core::ffi::c_int,
        channels as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured forced number of channels.
  ///
  /// # Returns
  ///
  /// An [`OpusEncForcedChannels`] variant representing the current forced
  /// channel configuration of the encoder, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_force_channels(&mut self) -> Result<OpusEncForcedChannels, OpusEncError> {
    let mut channels: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetForceChannels as core::ffi::c_int,
        core::ptr::from_mut(&mut channels),
      ) {
        0 => Ok(OpusEncForcedChannels::from_native(channels)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the maximum bandpass that the encoder will select automatically.
  ///
  /// Applications should normally use this instead of [`OpusEnc::set_bandwidth`]
  /// to allow the encoder to select the bandpass based on the available bitrate.
  ///
  /// # Arguments
  ///
  /// * `bandwidth` - The desired maximum bandpass for the encoder, which should be a variant of [`OpusEncBandwidth`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_max_bandwidth(&mut self, bandwidth: OpusEncBandwidth) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetMaxBandwidth as core::ffi::c_int,
        bandwidth as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured maximum allowed bandpass.
  ///
  /// # Returns
  ///
  /// An [`OpusEncBandwidth`] variant representing the maximum bandpass that
  /// the encoder will select automatically, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_max_bandwidth(&mut self) -> Result<OpusEncBandwidth, OpusEncError> {
    let mut bandwidth: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetMaxBandwidth as core::ffi::c_int,
        core::ptr::from_mut(&mut bandwidth),
      ) {
        0 => Ok(OpusEncBandwidth::from_native(bandwidth)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the type of signal being encoded, where [`OpusEncSignalBias::LpcHybrid`]
  /// should be used for a voice-like signal, and [`OpusEncSignalBias::MDCT`] should be used
  /// for music-like signals.
  ///
  /// This is a hint which helps the encoder's mode selection.
  ///
  /// # Arguments
  ///
  /// * `signal` - The desired signal type for the encoder, which should be a variant of [`OpusEncSignalBias`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_signal_bias(&mut self, signal: OpusEncSignalBias) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetSignal as core::ffi::c_int,
        signal as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured signal type.
  ///
  /// # Returns
  ///
  /// An [`OpusEncSignalBias`] variant, where [`OpusEncSignalBias::LpcHybrid`]
  /// indicates a voice-like signal, and [`OpusEncSignalBias::MDCT`] indicates a music-like
  /// signal, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_signal_bias(&mut self) -> Result<OpusEncSignalBias, OpusEncError> {
    let mut signal: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetSignal as core::ffi::c_int,
        core::ptr::from_mut(&mut signal),
      ) {
        0 => Ok(OpusEncSignalBias::from_native(signal)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's intended application.
  ///
  /// # Arguments
  ///
  /// * `application` - The desired application type for the encoder, which should be a variant of [`OpusEncApplication`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_application(&mut self, application: OpusEncApplication) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetApplication as core::ffi::c_int,
        application as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured application.
  ///
  /// # Returns
  ///
  /// An [`OpusEncApplication`] variant representing the current application
  /// setting of the encoder, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_application(&mut self) -> Result<OpusEncApplication, OpusEncError> {
    let mut application: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetApplication as core::ffi::c_int,
        core::ptr::from_mut(&mut application),
      ) {
        0 => Ok(OpusEncApplication::from_native(application)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the total number of delay samples added by the entire codec.
  ///
  /// This can be queried by the encoder, and then the provided number of samples can
  /// be skipped from the start of the decoder's output to provide time-aligned input
  /// and output. From the perspective of a decoding application, the real audio data
  /// begins this many samples late.
  ///
  /// The decoder contribution to this delay is identical for all decoders, but the
  /// encoder portion may vary from implementation to implementation, version to version,
  /// or even depend on the encoder's initial configuration. Applications needing
  /// delay compensation should rely on this function rather than hard-coding a value.
  ///
  /// # Returns
  ///
  /// The total number of delay samples added by the entire codec as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_lookahead(&mut self) -> Result<i32, OpusEncError> {
    let mut lookahead: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetLookahead as core::ffi::c_int,
        core::ptr::from_mut(&mut lookahead),
      ) {
        0 => Ok(lookahead),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's use of in-band Forward Error Correction (FEC).
  ///
  /// # Arguments
  ///
  /// * `fec` - A boolean value indicating whether to enable (`true`) or disable (`false`) in-band FEC for the encoder.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_inband_fec(&mut self, fec: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetInbandFec as core::ffi::c_int,
        core::ffi::c_int::from(fec),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured in-band Forward Error Correction (FEC) state.
  ///
  /// # Returns
  ///
  /// `True` if in-band FEC is enabled, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_inband_fec(&mut self) -> Result<bool, OpusEncError> {
    let mut fec: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetInbandFec as core::ffi::c_int,
        core::ptr::from_mut(&mut fec),
      ) {
        0 => Ok(fec != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's expected packet loss percentage, in the range 0-100.
  ///
  /// Higher values trigger progressively more loss-resistant behavior in the encoder
  /// at the expense of quality at a given bitrate in the absence of packet loss, but
  /// greater quality under loss.
  ///
  /// # Arguments
  ///
  /// * `loss_perc` - The desired expected packet loss percentage, ranging from 0 to 100.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_packet_loss_perc(&mut self, loss_perc: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetPacketLossPerc as core::ffi::c_int,
        loss_perc.clamp(0, 100) as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured packet loss percentage in the range 0-100.
  ///
  /// # Returns
  ///
  /// The current packet loss percentage setting of the encoder as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_packet_loss_perc(&mut self) -> Result<i32, OpusEncError> {
    let mut loss_perc: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetPacketLossPerc as core::ffi::c_int,
        core::ptr::from_mut(&mut loss_perc),
      ) {
        0 => Ok(loss_perc),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Sets whether Discontinuous Transmission (DTX) is enabled or disabled.
  ///
  /// # Arguments
  ///
  /// * `enabled` - A boolean value indicating whether to enable (`true`) or disable (`false`) DTX for the encoder.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_dtx_enabled(&mut self, enabled: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetDtx as core::ffi::c_int,
        core::ffi::c_int::from(enabled),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets whether Discontinuous Transmission (DTX) is enabled or disabled.
  ///
  /// # Returns
  ///
  /// `True` if DTX is enabled, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_dtx_enabled(&mut self) -> Result<bool, OpusEncError> {
    let mut dtx: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetDtx as core::ffi::c_int,
        core::ptr::from_mut(&mut dtx),
      ) {
        0 => Ok(dtx != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the depth (bit precision) of the signal being encoded.
  ///
  /// This is a hint which helps the encoder identify silence and near-silence. It
  /// represents the number of significant bits of linear intensity below which the signal
  /// contains ignorable quantization or other noise.
  ///
  /// For example, a bit-depth of 14 would be appropriate for G.711 u-law input. A bit-depth
  /// of 16 would be appropriate for 16-bit linear PCM input.
  ///
  /// # Arguments
  ///
  /// * `depth` - The desired bit depth for the encoder, which should be an `i32` representing the number of valid significant bits.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_lsb_depth(&mut self, depth: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetLsbDepth as core::ffi::c_int,
        depth as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured signal depth (input precision in bits).
  ///
  /// # Returns
  ///
  /// The current signal depth of the encoder as an `i32`, or an error
  /// if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_lsb_depth(&mut self) -> Result<i32, OpusEncError> {
    let mut depth: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetLsbDepth as core::ffi::c_int,
        core::ptr::from_mut(&mut depth),
      ) {
        0 => Ok(depth),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's use of variable duration frames.
  ///
  /// When variable duration is enabled, the encoder is free to use a shorter frame size
  /// than the one requested during encoder initialization. It is then the user's
  /// responsibility to verify how much audio was encoded by checking the `ToC` byte
  /// of the encoded packet. The part of the audio that was not encoded needs to be
  /// resent to the encoder for the next call.
  ///
  /// Do not use this option unless you **really** know what you are doing.
  ///
  /// # Arguments
  ///
  /// * `duration` - The length of the variable duration frame in milliseconds, which should be a variant of [`OpusEncFrameSize`].
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_expert_frame_duration(&mut self, duration: OpusEncFrameSize) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetExpertFrameDuration as core::ffi::c_int,
        duration as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured use of variable duration frames.
  ///
  /// # Returns
  ///
  /// An [`OpusEncFrameSize`] representing the current frame duration
  /// setting of the encoder, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_expert_frame_duration(&mut self) -> Result<OpusEncFrameSize, OpusEncError> {
    let mut duration: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetExpertFrameDuration as core::ffi::c_int,
        core::ptr::from_mut(&mut duration),
      ) {
        0 => Ok(OpusEncFrameSize::from_native(duration)),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Disables almost all use of prediction, making frames almost completely
  /// independent. This reduces quality.
  ///
  /// # Arguments
  ///
  /// * `disabled` - A boolean value indicating whether to disable (`true`) or enable (`false`) prediction in the encoder.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_prediction_disabled(&mut self, disabled: bool) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetPredictionDisabled as core::ffi::c_int,
        core::ffi::c_int::from(disabled),
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured prediction status.
  ///
  /// # Returns
  ///
  /// `True` if prediction is disabled (meaning that the encoder will not use
  /// prediction for encoding frames), and `False` if it is enabled,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_prediction_disabled(&mut self) -> Result<bool, OpusEncError> {
    let mut disabled: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetPredictionDisabled as core::ffi::c_int,
        core::ptr::from_mut(&mut disabled),
      ) {
        0 => Ok(disabled != 0),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Enables Deep Redundancy (DRED) with any non-zero value, specifying the maximum
  /// number of 10-ms redundant frames to be used.
  ///
  /// # Arguments
  ///
  /// * `duration` - The maximum number of 10-ms redundant frames to use for deep redundancy.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_dred_duration(&mut self, duration: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetDredDuration as core::ffi::c_int,
        duration as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured Deep Redundancy (DRED) maximum number of frames.
  ///
  /// # Returns
  ///
  /// The current maximum number of 10-ms redundant frames that the encoder
  /// is configured to use for Deep Redundancy (DRED) an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_dred_duration(&mut self) -> Result<i32, OpusEncError> {
    let mut duration: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetDredDuration as core::ffi::c_int,
        core::ptr::from_mut(&mut duration),
      ) {
        0 => Ok(duration),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Provides external DNN weights from a binary object.
  ///
  /// This should only be used when the library was explicitly built
  /// without the weights.
  ///
  /// # Arguments
  ///
  /// * `blob` - A byte slice representing the binary data of the DNN weights.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_truncation, clippy::cast_possible_wrap)]
  pub fn set_dnn_blob(&mut self, blob: &[u8]) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetDnnBlob as core::ffi::c_int,
        blob.as_ptr(),
        blob.len() as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's delay due to use of a DNN-based denoiser.
  ///
  /// # Arguments
  ///
  /// * `delay` - The desired delay in milliseconds introduced by the DNN-based denoiser.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_decision_delay(&mut self, delay: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetDecisionDelay as core::ffi::c_int,
        delay as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured delay due to use of a DNN-based denoiser.
  ///
  /// # Returns
  ///
  /// The current delay due to the DNN-based denoiser as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_decision_delay(&mut self) -> Result<i32, OpusEncError> {
    let mut delay: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetDecisionDelay as core::ffi::c_int,
        core::ptr::from_mut(&mut delay),
      ) {
        0 => Ok(delay),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the encoder's delay due to Ogg multiplexing.
  ///
  /// # Arguments
  ///
  /// * `delay` - The desired delay in milliseconds introduced by Ogg multiplexing.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_muxing_delay(&mut self, delay: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetMuxingDelay as core::ffi::c_int,
        delay as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured delay due to Ogg multiplexing.
  ///
  /// # Returns
  ///
  /// The current delay due to Ogg multiplexing as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_muxing_delay(&mut self) -> Result<i32, OpusEncError> {
    let mut delay: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetMuxingDelay as core::ffi::c_int,
        core::ptr::from_mut(&mut delay),
      ) {
        0 => Ok(delay),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the number of extra bytes to reserve for comments and metadata (defaults to 512).
  ///
  /// # Arguments
  ///
  /// * `padding` - The desired number of extra bytes to reserve for comments and metadata.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_comment_padding(&mut self, padding: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetCommentPadding as core::ffi::c_int,
        padding as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the encoder's configured number of extra bytes to reserve for comments and metadata.
  ///
  /// # Returns
  ///
  /// The current number of extra bytes reserved for comments and metadata as an `i32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_comment_padding(&mut self) -> Result<i32, OpusEncError> {
    let mut padding: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetCommentPadding as core::ffi::c_int,
        core::ptr::from_mut(&mut padding),
      ) {
        0 => Ok(padding),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Assigns a serial number to the current stream.
  ///
  /// # Arguments
  ///
  /// * `serial_no` - The desired serial number for the stream.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_wrap)]
  pub fn set_serial_no(&mut self, serial_no: u32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetSerialNo as core::ffi::c_int,
        serial_no as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the serial number of the current stream.
  ///
  /// # Returns
  ///
  /// The current serial number of the OggOpus stream as a `u32`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_sign_loss)]
  pub fn get_serial_no(&mut self) -> Result<u32, OpusEncError> {
    let mut serial_no: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetSerialNo as core::ffi::c_int,
        core::ptr::from_mut(&mut serial_no),
      ) {
        0 => Ok(serial_no as u32),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Configures the amount of gain to apply upon playback.
  ///
  /// **0 dB is recommended unless you know what you are doing.**
  ///
  /// # Arguments
  ///
  /// * `gain` - The desired gain in decibels (dB) to apply to the audio signal upon playback.
  ///
  /// # Returns
  ///
  /// A mutable reference to the current instance of [`OpusEnc`] if successful,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn set_header_gain(&mut self, gain: i32) -> Result<&mut Self, OpusEncError> {
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::SetHeaderGain as core::ffi::c_int,
        gain as core::ffi::c_int,
      ) {
        0 => Ok(self),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the amount of gain to apply upon playback.
  ///
  /// # Returns
  ///
  /// The current gain value in decibels (dB) that will be applied to the
  /// encoded stream upon playback as an `i32`, or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  pub fn get_header_gain(&mut self) -> Result<i32, OpusEncError> {
    let mut gain: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetHeaderGain as core::ffi::c_int,
        core::ptr::from_mut(&mut gain),
      ) {
        0 => Ok(gain),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the number of streams in the current OggOpus stream.
  ///
  /// # Returns
  ///
  /// The number of streams in the current OggOpus stream as a `u8`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
  pub fn get_nb_streams(&mut self) -> Result<u8, OpusEncError> {
    let mut nb_streams: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetNbStreams as core::ffi::c_int,
        core::ptr::from_mut(&mut nb_streams),
      ) {
        0 => Ok(nb_streams as u8),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }

  /// Gets the number of coupled streams in the current OggOpus stream.
  ///
  /// # Returns
  ///
  /// The number of coupled streams in the current OggOpus stream as a `u8`,
  /// or an error if the operation failed.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon operation failure.
  #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
  pub fn get_nb_coupled_streams(&mut self) -> Result<u8, OpusEncError> {
    let mut nb_coupled_streams: core::ffi::c_int = 0;
    unsafe {
      match ope::ope_encoder_ctl(
        self.ptr,
        OpusEncRequest::GetNbCoupledStreams as core::ffi::c_int,
        core::ptr::from_mut(&mut nb_coupled_streams),
      ) {
        0 => Ok(nb_coupled_streams as u8),
        err => Err(OpusEncError::from_native(err)),
      }
    }
  }
}

/// Provides methods for creating and managing an Opus encoder.
pub struct OpusEncoder;

impl OpusEncoder {
  /// Creates a new OggOpus file and encoder.
  ///
  /// # Arguments
  ///
  /// * `path` - Path where the file should be created
  /// * `comments` - Comments and metadata associated with the stream
  /// * `rate` - Sampling rate of the input audio
  /// * `channels` - Number of channels in the input audio
  /// * `family` - Channel mapping family (mono/stereo or surround)
  ///
  /// # Returns
  ///
  /// Newly-created [`OpusEnc`] encoder that can be used to encode audio
  /// into the specified OggOpus file.
  ///
  /// # Errors
  ///
  /// A [`OpusEncError::RustStringConversion`] error will be returned
  /// if conversion of the `path` to a C string fails.
  ///
  /// Any [`OpusEncError`] variant may be returned upon failure to create
  /// the encoder.
  pub fn create_file<'a>(
    path: &str,
    comments: &'a mut OpusEncComments,
    rate: OpusEncSampleRate,
    channels: u8,
    family: OpusEncChannelMapping,
  ) -> Result<Box<OpusEnc<'a, ()>>, OpusEncError> {
    let mut error = core::ffi::c_int::default();
    let path = CString::new(path).map_err(|_| OpusEncError::RustStringConversion)?;
    unsafe {
      let encoder = ope::ope_encoder_create_file(
        path.as_ptr(),
        comments.ptr,
        rate as ope::opus_int32,
        core::ffi::c_int::from(channels),
        family as core::ffi::c_int,
        core::ptr::from_mut(&mut error),
      );
      if encoder.is_null() {
        Err(OpusEncError::from_native(error))
      } else {
        Ok(Box::new(OpusEnc {
          ptr: encoder,
          write_cb: None,
          close_cb: None,
          cb_user_data: None,
        }))
      }
    }
  }

  /// Creates a new OggOpus stream to be manipulated using callbacks.
  ///
  /// This method allows for more control over the encoding process by using
  /// callbacks for writing encoded audio data and closing the stream. This is
  /// particularly useful for applications that need to handle the encoded
  /// data in a custom way, such as streaming it over a network or writing it
  /// to a custom output format.
  ///
  /// The `write_callback` will be invoked every time there is encoded audio data
  /// available for writing to a file, and the `close_callback` will be invoked when the
  /// audio stream is ready to be closed.
  ///
  /// # Arguments
  ///
  /// * `write_callback` - Callback function to handle writing encoded audio data
  /// * `close_callback` - Callback function to handle closing the stream
  /// * `user_data` - User-defined data to pass to the callback functions (such as a file pointer)
  /// * `comments` - Comments and metadata associated with the stream
  /// * `rate` - Sampling rate of the input audio
  /// * `channels` - Number of channels in the input audio
  /// * `family` - Channel mapping family (mono/stereo or surround)
  ///
  /// # Returns
  ///
  /// Newly-created [`OpusEnc`] encoder that can be used to encode audio using
  /// the provided callback functions.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon failure to create
  /// the encoder.
  pub fn create_callbacks<'a, T>(
    write_callback: OpeWriteFunc<T>,
    close_callback: OpeCloseFunc<T>,
    user_data: Option<&'a mut T>,
    comments: &mut OpusEncComments,
    rate: OpusEncSampleRate,
    channels: u8,
    family: OpusEncChannelMapping,
  ) -> Result<Box<OpusEnc<'a, T>>, OpusEncError> {
    let mut error = core::ffi::c_int::default();
    let native_callbacks = ope::OpusEncCallbacks {
      write: Some(OpusEnc::<T>::write_cb),
      close: Some(OpusEnc::<T>::close_cb),
    };
    let mut enc = Box::new(OpusEnc {
      ptr: core::ptr::null_mut(),
      write_cb: Some(write_callback),
      close_cb: Some(close_callback),
      cb_user_data: user_data,
    });
    unsafe {
      let encoder = ope::ope_encoder_create_callbacks(
        &native_callbacks,
        core::ptr::from_mut(enc.as_mut()).cast(),
        comments.ptr,
        rate as ope::opus_int32,
        core::ffi::c_int::from(channels),
        family as core::ffi::c_int,
        core::ptr::from_mut(&mut error),
      );
      if encoder.is_null() {
        Err(OpusEncError::from_native(error))
      } else {
        enc.ptr = encoder;
        Ok(enc)
      }
    }
  }

  /// Creates a new OggOpus stream to be used along with [`OpusEnc::get_page`].
  ///
  /// This is mostly useful for muxing with other streams.
  ///
  /// # Arguments
  ///
  /// * `comments` - Comments and metadata associated with the stream
  /// * `rate` - Sampling rate of the input audio
  /// * `channels` - Number of channels in the input audio
  /// * `family` - Channel mapping family (mono/stereo or surround)
  ///
  /// # Returns
  ///
  /// Newly-created [`OpusEnc`] encoder that can be used to encode audio
  /// into an OggOpus stream accessible via the [`OpusEnc::get_page`] function.
  ///
  /// # Errors
  ///
  /// Any [`OpusEncError`] variant may be returned upon failure to create
  /// the encoder.
  pub fn create_pull<'a>(
    comments: &mut OpusEncComments,
    rate: OpusEncSampleRate,
    channels: u8,
    family: OpusEncChannelMapping,
  ) -> Result<Box<OpusEnc<'a, ()>>, OpusEncError> {
    let mut error = core::ffi::c_int::default();
    unsafe {
      let encoder = ope::ope_encoder_create_pull(
        comments.ptr,
        rate as ope::opus_int32,
        core::ffi::c_int::from(channels),
        family as core::ffi::c_int,
        core::ptr::from_mut(&mut error),
      );
      if encoder.is_null() {
        Err(OpusEncError::from_native(error))
      } else {
        Ok(Box::new(OpusEnc {
          ptr: encoder,
          write_cb: None,
          close_cb: None,
          cb_user_data: None,
        }))
      }
    }
  }
}

#[cfg(test)]
mod tests {
  use alloc::vec::Vec;
  use std::io::Write;

  fn read_wav_file(path: &str) -> Vec<i16> {
    let wav_reader = hound::WavReader::open(path).expect("Failed to open WAV file");
    wav_reader
      .into_samples::<i16>()
      .collect::<Result<Vec<_>, _>>()
      .expect("Failed to read WAV file")
  }

  #[test]
  fn test_file_encoding() {
    let audio = read_wav_file("test_assets/wav_test1.wav");
    let mut comments = crate::OpusEncComments::create().expect("Failed to create OpusEncComments");
    comments
      .add("TITLE", "Some Track")
      .expect("Failed to add comment")
      .add_string("ARTIST=Test Artist")
      .expect("Failed to add comment string")
      .add_string("ALBUM=Test Album")
      .expect("Failed to add comment string");
    crate::OpusEncoder::create_file(
      "test_assets/test1.opus",
      &mut comments,
      crate::OpusEncSampleRate::Hz48000,
      1,
      crate::OpusEncChannelMapping::MonoStereo,
    )
    .expect("Failed to create OpusEnc")
    .set_vbr(true)
    .expect("Failed to set VBR")
    .set_complexity(10)
    .expect("Failed to set complexity")
    .set_bandwidth(crate::OpusEncBandwidth::SuperWideband12kHz)
    .expect("Failed to set bandwidth")
    .set_application(crate::OpusEncApplication::Audio)
    .expect("Failed to set application")
    .set_bitrate(crate::OpusEncBitrate::Explicit(24000))
    .expect("Failed to set bitrate")
    .write(&audio, 1)
    .expect("Failed to write audio");
  }

  #[test]
  fn test_file_encoding_callbacks() {
    fn write_callback(file: &mut std::fs::File, data: &[u8]) -> bool {
      file
        .write_all(data)
        .expect("Failed to write data to file from within callback");
      true
    }
    fn close_callback(_file: &mut std::fs::File) -> bool {
      true
    }

    let audio = read_wav_file("test_assets/wav_test1.wav");
    let mut output_file = std::fs::File::create("test_assets/test_cb.opus").expect("Failed to create output file");
    let mut comments = crate::OpusEncComments::create().expect("Failed to create OpusEncComments");
    comments
      .add("TITLE", "Some Track CB")
      .expect("Failed to add comment")
      .add_string("ARTIST=Test Artist CB")
      .expect("Failed to add comment string")
      .add_string("ALBUM=Test Album CB")
      .expect("Failed to add comment string");
    crate::OpusEncoder::create_callbacks(
      write_callback,
      close_callback,
      Some(&mut output_file),
      &mut comments,
      crate::OpusEncSampleRate::Hz48000,
      1,
      crate::OpusEncChannelMapping::MonoStereo,
    )
    .expect("Failed to create OpusEnc")
    .set_vbr(true)
    .expect("Failed to set VBR")
    .set_complexity(10)
    .expect("Failed to set complexity")
    .set_bandwidth(crate::OpusEncBandwidth::SuperWideband12kHz)
    .expect("Failed to set bandwidth")
    .set_application(crate::OpusEncApplication::Audio)
    .expect("Failed to set application")
    .set_bitrate(crate::OpusEncBitrate::Explicit(24000))
    .expect("Failed to set bitrate")
    .write(&audio, 1)
    .expect("Failed to write audio");
  }
}