modules.c
69.8 KB
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
/*
Audio File Library
Copyright (C) 2000, Silicon Graphics, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place - Suite 330,
Boston, MA 02111-1307 USA.
*/
/*
modules.c
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <assert.h>
#include <audiofile.h>
#include "afinternal.h"
#include "modules.h"
#include "pcm.h"
#include "util.h"
#include "units.h"
#include "compression.h"
#include "byteorder.h"
#include "print.h"
#include "modules/rebuffer.h"
#ifdef DEBUG
#define CHNK(X) X
#define DEBG(X) X
#else
#define CHNK(X)
#define DEBG(X)
#endif
#define NULLMODULEPARAM
extern _PCMInfo _af_default_signed_integer_pcm_mappings[];
extern _PCMInfo _af_default_unsigned_integer_pcm_mappings[];
extern _PCMInfo _af_default_float_pcm_mapping;
extern _PCMInfo _af_default_double_pcm_mapping;
extern _CompressionUnit _af_compression[];
/* Define rebuffering modules. */
extern _AFmodule int2rebufferv2f, int2rebufferf2v;
/*
module utility routines
*/
/*
_AFnewmodinst creates a module instance from a module.
It returns a structure, not a pointer to a structure.
*/
_AFmoduleinst _AFnewmodinst (_AFmodule *mod)
{
_AFmoduleinst ret;
ret.inc = ret.outc = NULL;
ret.modspec = NULL;
ret.u.pull.source = NULL;
ret.mod = mod;
ret.free_on_close = AF_FALSE;
ret.valid = AF_FALSE;
return(ret);
}
/*
_AFfreemodspec: useful routine for mod.free function pointer
*/
void _AFfreemodspec (_AFmoduleinst *i)
{
if (i->modspec)
free(i->modspec);
i->modspec = NULL;
}
/*
_AFpull: used a lot -- see comments in README.modules
*/
AFframecount _AFpull (_AFmoduleinst *i, AFframecount nframes2pull)
{
_AFmoduleinst *src = i->u.pull.source;
i->inc->nframes = nframes2pull;
CHNK(printf("%s pulling %" AF_FRAMECOUNT_PRINT_FMT " frames from %s\n",
i->mod->name, i->inc->nframes, src->mod->name));
(*src->mod->run_pull)(src);
CHNK(_af_print_chunk(i->inc));
CHNK(printf("%s received %" AF_FRAMECOUNT_PRINT_FMT " frames from %s\n",
i->mod->name, i->inc->nframes, src->mod->name));
return i->inc->nframes;
}
/*
_AFsimplemodrun
*/
void _AFsimplemodrun_pull (_AFmoduleinst *i)
{
_AFpull(i, i->outc->nframes);
(*i->mod->run)(i->inc, i->outc, i->modspec);
}
/*
_AFpush
*/
void _AFpush (_AFmoduleinst *i, AFframecount nframes2push)
{
_AFmoduleinst *snk = i->u.push.sink;
i->outc->nframes = nframes2push;
CHNK(printf("%s pushing %" AF_FRAMECOUNT_PRINT_FMT " frames into %s\n",
i->mod->name, i->outc->nframes, snk->mod->name));
CHNK(_af_print_chunk(i->outc));
(*(snk->mod->run_push))(snk);
}
/*
_AFpushat
*/
void _AFpushat (_AFmoduleinst *i, AFframecount startframe, bool stretchint,
AFframecount nframes2push)
{
_AFmoduleinst *snk = i->u.push.sink;
void *saved_buf = i->outc->buf;
i->outc->buf = ((char *)i->outc->buf) +
(_af_format_frame_size_uncompressed(&i->outc->f,stretchint) * startframe);
i->outc->nframes = nframes2push;
CHNK(printf("%s pushing %" AF_FRAMECOUNT_PRINT_FMT " frames into %s "
"with OFFSET %" AF_FILEOFFSET_PRINT_FMT " frames\n",
i->mod->name, i->outc->nframes, snk->mod->name, startframe));
CHNK(_af_print_chunk(i->outc));
(*(snk->mod->run_push))(snk);
i->outc->buf = saved_buf;
}
/*
_AFsimplemodrun
*/
void _AFsimplemodrun_push (_AFmoduleinst *i)
{
i->outc->nframes = i->inc->nframes;
(*(i->mod->run))(i->inc, i->outc, i->modspec);
_AFpush(i, i->outc->nframes);
}
/*
These macros each declare a module.
The module uses _AFsimplemodrun_pull and _AFsimplemodrun_push
(see comments in README.modules). Thus we only have to define
one routine that does the actual processing.
The arguments to the macros are as follows:
name - name of module
desc - code for module's "describe" function (see README.modules)
intype - type of elements of input buffer
outtype - type of elements of output buffer
action - action to take in inner loop -- indexes "ip" and "op" with "i"
modspectype - (MODULEM) this will initialize a pointer "m"
to this instance's modspec data, which is of type modspectype
Don't use _MODULE directly.
The code in "desc" is executed once, after the module is
initialized. It can reference "i->modspec" and should modify
"i->outc->f". A pointer "f" initialized to "&i->outc->f" is
emitted prior to "desc"; use this to to keep the code cleaner.
Note that the generated "run" routine shouldn't set outc->nframes since
* outc->nframes is set to inc->nframes by _AFsimplemodrun_push
* inc->nframes is set to outc->nframes by _AFsimplemodrun_pull
The whole point of the simplified "run" routine is that you don't
have to worry about push or pull.
See README.modules for more info on how modules work.
*/
#define _MODULE( name, desc, \
intype, outtype, chans, preamble, action, postamble )\
void name##run(_AFchunk *inc, _AFchunk *outc, void *modspec)\
{\
intype *ip = inc->buf;\
outtype *op = outc->buf;\
int count = inc->nframes * (chans);\
int i;\
\
preamble;\
for(i=0; i < count; ++i) \
action;\
postamble;\
}\
\
void name##describe(struct _AFmoduleinst *i)\
{\
_AudioFormat *f = &i->outc->f; \
desc;\
}\
\
_AFmodule name =\
{ \
#name,\
name##describe, \
AF_NULL, AF_NULL, \
_AFsimplemodrun_pull, AF_NULL, AF_NULL, \
_AFsimplemodrun_push, AF_NULL, AF_NULL, \
name##run, \
_AFfreemodspec \
};
#define MODULE(name, desc, intype, outtype, action)\
_MODULE(name, desc, intype, outtype, inc->f.channelCount, \
NULLMODULEPARAM, action, NULLMODULEPARAM)
#define MODULEM(name, desc, intype, outtype, modspectype, action)\
_MODULE(name, desc, intype, outtype, inc->f.channelCount, \
modspectype *m = (modspectype *) modspec, action, NULLMODULEPARAM)
/*
Byte-order-swapping modules.
*/
#define MODULESWAP(name, type, action) \
MODULE(name, \
f->byteOrder = (f->byteOrder==AF_BYTEORDER_LITTLEENDIAN) ?\
AF_BYTEORDER_BIGENDIAN : AF_BYTEORDER_LITTLEENDIAN,\
type, type,\
action)
MODULESWAP(swap2, uchar2,
{ char3u u; uchar1 c; u.uchar2.s0 = ip[i];
c = u.uchar1.c1; u.uchar1.c1 = u.uchar1.c0; u.uchar1.c0 = c;
op[i] = u.uchar2.s0; })
MODULESWAP(swap3, real_char3,
{ char3u u; uchar1 c; u.real_char3_low.c3 = ip[i];
c = u.uchar1.c3; u.uchar1.c3 = u.uchar1.c1; u.uchar1.c1 = c;
op[i] = u.real_char3_low.c3; })
MODULESWAP(swap4, uchar4,
{ char3u u; uchar1 c; u.uchar4.i = ip[i];
c = u.uchar1.c3; u.uchar1.c3 = u.uchar1.c0; u.uchar1.c0 = c;
c = u.uchar1.c1; u.uchar1.c1 = u.uchar1.c2; u.uchar1.c2 = c;
op[i] = u.uchar4.i; })
MODULESWAP(swap8, real_char8,
{ real_char8 *i8 = &ip[i]; real_char8 *o8 = &op[i];
o8->c0 = i8->c7;
o8->c1 = i8->c6;
o8->c2 = i8->c5;
o8->c3 = i8->c4;
o8->c4 = i8->c3;
o8->c5 = i8->c2;
o8->c6 = i8->c1;
o8->c7 = i8->c0; })
/*
modules for dealing with 3-byte integers
*/
/* convert 0xaabbcc to 0xssaabbcc */
#ifdef WORDS_BIGENDIAN
MODULE(real_char3_to_schar3, f /* NOTUSED */, real_char3, schar3,
{
char3u u;
u.real_char3_high.c3 = ip[i];
u.real_char3_high.pad = 0;
op[i] = u.schar3.i >> 8;
})
#else
MODULE(real_char3_to_schar3, f /* NOTUSED */, real_char3, schar3,
{
char3u u;
u.real_char3_low.c3 = ip[i];
u.real_char3_low.pad = 0;
op[i] = u.schar3.i >> 8;
})
#endif
/* convert 0xaabbcc to 0x00aabbcc */
#ifdef WORDS_BIGENDIAN
MODULE(real_char3_to_uchar3, f /* NOTUSED */, real_char3, uchar3,
{
char3u u;
u.real_char3_high.c3 = ip[i];
u.real_char3_high.pad = 0;
op[i] = u.uchar3.i >> 8;
})
#else
MODULE(real_char3_to_uchar3, f /* NOTUSED */, real_char3, uchar3,
{
char3u u;
u.real_char3_low.c3 = ip[i];
u.real_char3_low.pad = 0;
op[i] = u.uchar3.i >> 8;
})
#endif
/* convert 0x??aabbcc to 0xaabbcc */
#ifdef WORDS_BIGENDIAN
MODULE(char3_to_real_char3, f /* NOTUSED */, uchar3, real_char3,
{
char3u u;
u.uchar3.i = ip[i];
op[i] = u.real_char3_low.c3;
})
#else
MODULE(char3_to_real_char3, f /* NOTUSED */, uchar3, real_char3,
{
char3u u;
u.uchar3.i = ip[i];
op[i] = u.real_char3_high.c3;
})
#endif
/*
float <--> double ; CASTS
*/
MODULE(float2double, f->sampleFormat = AF_SAMPFMT_DOUBLE,
float, double, op[i] = ip[i] )
MODULE(double2float, f->sampleFormat = AF_SAMPFMT_FLOAT,
double, float, op[i] = ip[i] )
/*
int2floatN - expects 8N-bit 2's comp ints, outputs floats ; CASTS
*/
MODULE(int2float1, f->sampleFormat = AF_SAMPFMT_FLOAT,
schar1, float, op[i] = ip[i])
MODULE(int2float2, f->sampleFormat = AF_SAMPFMT_FLOAT,
schar2, float, op[i] = ip[i])
MODULE(int2float3, f->sampleFormat = AF_SAMPFMT_FLOAT,
schar3, float, op[i] = ip[i])
MODULE(int2float4, f->sampleFormat = AF_SAMPFMT_FLOAT,
schar4, float, op[i] = ip[i])
/*
int2doubleN - expects 8N-bit 2's comp ints, outputs doubles ; CASTS
*/
MODULE(int2double1, f->sampleFormat = AF_SAMPFMT_DOUBLE,
schar1, double, op[i] = ip[i])
MODULE(int2double2, f->sampleFormat = AF_SAMPFMT_DOUBLE,
schar2, double, op[i] = ip[i])
MODULE(int2double3, f->sampleFormat = AF_SAMPFMT_DOUBLE,
schar3, double, op[i] = ip[i])
MODULE(int2double4, f->sampleFormat = AF_SAMPFMT_DOUBLE,
schar4, double, op[i] = ip[i])
/*
The following modules perform the transformation between one
pcm mapping and another.
The modules all use MODULETRANS; some of them also perform
clipping.
Use initpcmmod() to create an instance of any of these modules.
initpcmmod() takes an _PCMInfo describing the desired output
pcm mapping.
*/
typedef struct pcmmodspec
{
/* These are the computed parameters of the transformation. */
double m, b;
double maxv, minv;
/* This is what goes in i->outc->f. */
_PCMInfo output_mapping;
} pcmmodspec;
/*
initpcmmod
*/
_AFmoduleinst initpcmmod (_AFmodule *mod,
_PCMInfo *input_mapping, _PCMInfo *output_mapping)
{
_AFmoduleinst ret = _AFnewmodinst(mod);
pcmmodspec *m = _af_malloc(sizeof (pcmmodspec));
ret.modspec = m;
/* Remember output mapping for use in the describe function. */
m->output_mapping = *output_mapping;
/*
Compute values needed to perform transformation if the module
being initialized does a transformation..
*/
if (input_mapping)
{
m->m = output_mapping->slope / input_mapping->slope;
m->b = output_mapping->intercept - m->m * input_mapping->intercept;
}
/* Remember clip values. */
m->minv = output_mapping->minClip;
m->maxv = output_mapping->maxClip;
return ret;
}
#define MODULETRANS( name, xtradesc, intype, outtype, action ) \
MODULEM(name, \
{ \
f->pcm = ((pcmmodspec *) i->modspec)->output_mapping; \
xtradesc; \
}, \
intype, outtype, pcmmodspec, \
action)
MODULETRANS(floattransform, NULLMODULEPARAM, float, float, \
op[i]=(m->b + m->m * ip[i]))
MODULETRANS(doubletransform, NULLMODULEPARAM, double, double, \
op[i]=(m->b + m->m * ip[i]))
/*
float2intN_clip - expects floats,
outputs CLIPped, 8N-bit, transformed 2's comp ints
double2intN_clip - same deal with doubles
*/
#define TRANS_CLIP(type) \
{\
double d=(m->b + m->m * ip[i]); \
op[i] = \
(((type)((d>(m->maxv)) ? (m->maxv) : ((d<(m->minv))?(m->minv):d)))); \
}
MODULETRANS(float2int1_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 8; },
float, schar1, TRANS_CLIP(schar1))
MODULETRANS(float2int2_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 16; },
float, schar2, TRANS_CLIP(schar2))
MODULETRANS(float2int3_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 24; },
float, schar3, TRANS_CLIP(schar3))
MODULETRANS(float2int4_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 32; },
float, schar4, TRANS_CLIP(schar4))
MODULETRANS(double2int1_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 8; },
double, schar1, TRANS_CLIP(schar1))
MODULETRANS(double2int2_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 16; },
double, schar2, TRANS_CLIP(schar2))
MODULETRANS(double2int3_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 24; },
double, schar3, TRANS_CLIP(schar3))
MODULETRANS(double2int4_clip,
{ f->sampleFormat = AF_SAMPFMT_TWOSCOMP; f->sampleWidth = 32; },
double, schar4, TRANS_CLIP(schar4))
/*
clipping modules - use initpcmmod() to make one of these
clips to range given as argument to init function.
*/
#define MODULECLIP(name, type)\
MODULEM(name, \
{ f->pcm = ((pcmmodspec *)i->modspec)->output_mapping; }, \
type, type, pcmmodspec, \
{ \
type d=ip[i]; \
type min=(type)(m->minv); \
type max=(type)(m->maxv); \
op[i] = ((d>max) ? max : ((d<min) ? min : d)); \
} )
MODULECLIP(clipfloat, float)
MODULECLIP(clipdouble, double)
MODULECLIP(clip1, schar1)
MODULECLIP(clip2, schar2)
MODULECLIP(clip3, schar3)
MODULECLIP(clip4, schar4)
/*
unsigned2signedN - expects 8N-bit unsigned ints, outputs 2's comp
*/
MODULE(unsigned2signed1,
{
double shift = (double) MIN_INT8;
f->sampleFormat = AF_SAMPFMT_TWOSCOMP;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
uchar1, schar1,
op[i] = ip[i] + MIN_INT8)
MODULE(unsigned2signed2,
{
double shift = (double) MIN_INT16;
f->sampleFormat = AF_SAMPFMT_TWOSCOMP;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
uchar2, schar2,
op[i] = ip[i] + MIN_INT16)
MODULE(unsigned2signed3,
{
double shift = (double) MIN_INT24;
f->sampleFormat = AF_SAMPFMT_TWOSCOMP;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
uchar3, schar3,
op[i] = ip[i] + MIN_INT24)
MODULE(unsigned2signed4,
{
double shift = (double) MIN_INT32;
f->sampleFormat = AF_SAMPFMT_TWOSCOMP;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
uchar4, schar4,
op[i] = ip[i] + MIN_INT32)
/* !! unsigned2signed4 shouldn't work, but it does !! */
/*
signed2unsignedN - expects 8N-bit 2's comp ints, outputs unsigned
*/
MODULE(signed2unsigned1,
{
double shift = -(double) MIN_INT8;
f->sampleFormat = AF_SAMPFMT_UNSIGNED;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
schar1, uchar1,
op[i] = ip[i] - MIN_INT8)
MODULE(signed2unsigned2,
{
double shift = -(double) MIN_INT16;
f->sampleFormat = AF_SAMPFMT_UNSIGNED;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
schar2, uchar2,
op[i] = ip[i] - MIN_INT16)
MODULE(signed2unsigned3,
{
double shift = -(double) MIN_INT24;
f->sampleFormat = AF_SAMPFMT_UNSIGNED;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
schar3, uchar3,
op[i] = ip[i] - MIN_INT24)
MODULE(signed2unsigned4,
{
double shift = -(double) MIN_INT32;
f->sampleFormat = AF_SAMPFMT_UNSIGNED;
f->pcm.intercept += shift;
f->pcm.minClip += shift;
f->pcm.maxClip += shift;
},
schar4, uchar4,
op[i] = ip[i] - MIN_INT32)
/* !! signed2unsigned4 shouldn't work, but it does !! */
/*
These convert between different 2's complement integer formats
with no roundoff/asymmetric errors. They should also work faster
than converting integers to floats and back to other integers.
They are only meant to be used when the input and output integers
have the default PCM mapping; otherwise, arrangemodules will
make the conversion go through floating point and these modules
will not be used.
*/
#define intmap _af_default_signed_integer_pcm_mappings /* shorthand */
MODULE(int1_2, { f->sampleWidth = 16; f->pcm=intmap[2]; },
schar1, schar2, op[i] = ip[i] << 8)
MODULE(int1_3, { f->sampleWidth = 24; f->pcm=intmap[3]; },
schar1, schar3, op[i] = ip[i] << 16)
MODULE(int1_4, { f->sampleWidth = 32; f->pcm=intmap[4]; },
schar1, schar4, op[i] = ip[i] << 24)
MODULE(int2_1, { f->sampleWidth = 8; f->pcm=intmap[1]; },
schar2, schar1, op[i] = ip[i] >> 8)
MODULE(int2_3, { f->sampleWidth = 24; f->pcm=intmap[3]; },
schar2, schar3, op[i] = ip[i] << 8)
MODULE(int2_4, { f->sampleWidth = 32; f->pcm=intmap[4]; },
schar2, schar4, op[i] = ip[i] << 16)
MODULE(int3_1, { f->sampleWidth = 8; f->pcm=intmap[1]; },
schar3, schar1, op[i] = ip[i] >> 16)
MODULE(int3_2, { f->sampleWidth = 16; f->pcm=intmap[2]; },
schar3, schar2, op[i] = ip[i] >> 8)
MODULE(int3_4, { f->sampleWidth = 32; f->pcm=intmap[4]; },
schar3, schar4, op[i] = ip[i] << 8)
MODULE(int4_1, { f->sampleWidth = 8; f->pcm=intmap[1]; },
schar4, schar1, op[i] = ip[i] >> 24)
MODULE(int4_2, { f->sampleWidth = 16; f->pcm=intmap[2]; },
schar4, schar2, op[i] = ip[i] >> 16)
MODULE(int4_3, { f->sampleWidth = 24; f->pcm=intmap[3]; },
schar4, schar3, op[i] = ip[i] >> 8)
#undef intmap
/*
channel changer modules - convert channels using channel matrix
The channel matrix is a two-dimensional array of doubles, the rows
of which correspond to the virtual format, and the columns
of which correspond to the file format.
If the channel matrix is null (unspecified), then the default
behavior occurs (see initchannelchange).
Internally, the module holds a copy of the matrix in which the
rows correspond to the output format, and the columns correspond
to the input format (therefore, if reading==AF_FALSE, the matrix
is transposed as it is copied).
*/
typedef struct channelchangedata
{
int outchannels;
double minClip;
double maxClip;
double *matrix;
} channelchangedata;
/*
channelchangefree
*/
void channelchangefree (struct _AFmoduleinst *i)
{
channelchangedata *d = i->modspec;
assert(d);
assert(d->matrix);
free(d->matrix);
free(d);
i->modspec = AF_NULL;
}
/*
channelchangedescribe
*/
void channelchangedescribe (struct _AFmoduleinst *i)
{
channelchangedata *m = (channelchangedata *) i->modspec;
i->outc->f.channelCount = m->outchannels;
i->outc->f.pcm.minClip = m->minClip;
i->outc->f.pcm.maxClip = m->maxClip;
}
#define CHANNELMOD( name, type, zero_op, action, afteraction ) \
void name##run(_AFchunk *inc, _AFchunk *outc, void *modspec) \
{ \
type *ip = inc->buf; \
type *op = outc->buf; \
double *matrix = ((channelchangedata *)modspec)->matrix; \
double *m; \
int frame, inch, outch; \
\
for (frame=0; frame < outc->nframes; frame++) \
{ \
type *ipsave; \
\
m = matrix; \
ipsave = ip; \
\
for (outch = 0; outch < outc->f.channelCount; outch++) \
{ \
zero_op; \
ip = ipsave; \
\
for (inch = 0; inch < inc->f.channelCount; inch++) \
action;\
\
afteraction; \
op++;\
}\
}\
}\
\
_AFmodule name =\
{ \
#name, \
channelchangedescribe, \
AF_NULL, AF_NULL, \
_AFsimplemodrun_pull, AF_NULL, AF_NULL, \
_AFsimplemodrun_push, AF_NULL, AF_NULL, \
name##run, \
channelchangefree \
};
CHANNELMOD(channelchangefloat, float, *op = 0.0, *op += *ip++ * *m++, \
NULLMODULEPARAM)
CHANNELMOD(channelchangedouble, double, *op = 0.0, *op += *ip++ * *m++, \
NULLMODULEPARAM)
#define CHANNELINTMOD(name, type) \
CHANNELMOD(name, type, \
double d=0.0, \
d += *ip++ * *m++, \
{ \
double minv=outc->f.pcm.minClip; \
double maxv=outc->f.pcm.maxClip; \
*op = (type) ((d>maxv) ? maxv : ((d<minv) ? minv : d)); \
} )
CHANNELINTMOD(channelchange1, schar1)
CHANNELINTMOD(channelchange2, schar2)
CHANNELINTMOD(channelchange3, schar3)
CHANNELINTMOD(channelchange4, schar4)
/*
initchannelchange
*/
_AFmoduleinst initchannelchange (_AFmodule *mod,
double *matrix, _PCMInfo *outpcm,
int inchannels, int outchannels,
bool reading)
{
_AFmoduleinst ret;
channelchangedata *d;
int i, j;
ret = _AFnewmodinst(mod);
d = _af_malloc(sizeof (channelchangedata));
ret.modspec = d;
d->outchannels = outchannels;
d->minClip = outpcm->minClip;
d->maxClip = outpcm->maxClip;
d->matrix = _af_malloc(sizeof (double) * inchannels * outchannels);
/*
Set d->matrix to a default matrix if a matrix was not specified.
*/
if (!matrix)
{
bool special=AF_FALSE;
/* Handle many common special cases. */
if (inchannels==1 && outchannels==2)
{
static double m[]={1,1};
matrix=m;
special=AF_TRUE;
}
else if (inchannels==1 && outchannels==4)
{
static double m[]={1,1,0,0};
matrix=m;
special=AF_TRUE;
}
else if (inchannels==2 && outchannels==1)
{
static double m[]={.5,.5};
matrix=m;
special=AF_TRUE;
}
else if (inchannels==2 && outchannels==4)
{
static double m[]={1,0,0,1,0,0,0,0};
matrix=m;
special=AF_TRUE;
}
else if (inchannels==4 && outchannels==1)
{
static double m[]={.5,.5,.5,.5};
matrix=m;
special=AF_TRUE;
}
else if (inchannels==4 && outchannels==2)
{
static double m[]={1,0,1,0,0,1,0,1};
matrix=m;
special=AF_TRUE;
}
else
{
/*
Each input channel from 1 to N
maps to output channel 1 to N where
N=min(inchannels, outchannels).
*/
for(i=0; i < inchannels; i++)
for(j=0; j < outchannels; j++)
d->matrix[j*inchannels + i] =
(i==j) ? 1.0 : 0.0;
}
if (special)
memcpy(d->matrix, matrix,
sizeof (double) * inchannels * outchannels);
}
/* Otherwise transfer matrix into d->matrix. */
else
{
/* reading: copy matrix */
if (reading)
{
memcpy(d->matrix, matrix, sizeof (double) * inchannels * outchannels);
}
/* writing: transpose matrix */
else
{
for (i=0; i < inchannels; i++)
for (j=0; j < outchannels; j++)
d->matrix[j*inchannels + i] =
matrix[i*outchannels + j];
}
}
DEBG(printf("channelchange d->matrix="));
DEBG(_af_print_channel_matrix(d->matrix, inchannels, outchannels));
DEBG(printf("\n"));
return(ret);
}
/* just used here */
typedef struct current_state
{
_AFmoduleinst *modinst; /* current mod instance we're creating */
_AFchunk *inchunk; /* current input chunk */
_AFchunk *outchunk; /* current output chunk */
} current_state;
/*
addmod is called once per added module instance. It does the
work of putting the module instance in the list and assigning
it an input and output chunk.
*/
void addmod (current_state *current, _AFmoduleinst modinst)
{
*(current->modinst) = modinst;
current->modinst->valid = AF_TRUE; /* at this point mod must be valid */
/* Assign the new module instance an input and an output chunk. */
current->modinst->inc = current->inchunk;
current->modinst->outc = current->outchunk;
/*
The output chunk has the same format and number of frames
as input chunk, except in whatever way the 'describe'
method tells us (see README.modules).
*/
*(current->outchunk) = *(current->inchunk);
if (current->modinst->mod->describe)
(*current->modinst->mod->describe)(current->modinst);
/*
Advance to next module and next chunks. Note that next
moduleinst will have this module's out chunk as input.
*/
current->modinst++;
current->inchunk = current->outchunk;
current->outchunk++;
}
/*
initfilemods:
Functions that deal with extended-lifetime file read / file write
modules and their extended-lifetime rebuffer modules.
called once in the lifetime of an AFfilehandle.
If h->access == _AF_READ_ACCESS:
Create the module which will be the first module in the chain,
the one which reads the file. This module does the decompression
if necessary, or it could just be a PCM file reader.
If h->access == _AF_WRITE_ACCESS:
Create the module which will be the last module in the chain,
the one which writes the file. This module does the compression
if necessary, or it could just be a PCM file writer.
Also creates a rebuffer module for these modules if necessary.
*/
status initfilemods (_Track *track, AFfilehandle h)
{
int compressionIndex;
_CompressionUnit *compunit;
AFframecount chunkframes;
compressionIndex = _af_compression_index_from_id(track->f.compressionType);
compunit = &_af_compression[compressionIndex];
/* Invalidate everything. */
track->ms.filemodinst.valid = AF_FALSE;
track->ms.filemod_rebufferinst.valid = AF_FALSE;
/*
Seek to beginning of sound data in the track.
This is needed ONLY for those modules which have to
read/write some kind of pre-data header or table in the
sound data chunk of the file (such as aware). This is NOT
the seek that sets the file at the beginning of the data.
*/
/* XXXmpruett -- we currently don't set seekok.
if (h->seekok && af_fseek(h->fh, track->fpos_first_frame, SEEK_SET) < 0)
*/
if (af_fseek(h->fh, track->fpos_first_frame, SEEK_SET) < 0)
{
_af_error(AF_BAD_LSEEK, "unable to position file handle at beginning of sound data");
return AF_FAIL;
}
/* Create file read/write module. */
track->filemodhappy = AF_TRUE;
if (h->access == _AF_READ_ACCESS)
track->ms.filemodinst =
(*compunit->initdecompress)(track, h->fh, h->seekok,
(h->fileFormat==AF_FILE_RAWDATA), &chunkframes);
else
track->ms.filemodinst =
(*compunit->initcompress)(track, h->fh, h->seekok,
(h->fileFormat==AF_FILE_RAWDATA), &chunkframes);
if (!track->filemodhappy)
return AF_FAIL;
track->ms.filemodinst.valid = AF_TRUE;
/*
WHEN DOES THE FILE GET LSEEKED ?
Somebody sometime has got to lseek the file to the
beginning of the audio data. Similarly, somebody
has to lseek the file at the time of reset or sync.
Furthermore, we have to make sure that we operate
correctly if more than one track is being read or written.
This is handled differently based on whether we are
reading or writing, and whether the ONE_TRACK_ONLY lseek
optimization is engaged.
READING:
If we are reading, the file needs to be positioned once
before we start reading and then once per seek.
If ONE_TRACK_ONLY is not defined, then there can
be multiple tracks in the file. Thus any call to
afReadFrames could cause the file pointer to be
put anywhere: we can not rely on the file pointer
tracking only one track in the file, thus we must seek
to the current position in track N whenever we begin
an AFreadframes on track N. Thus the lseek is done in
afReadFrames. When a reset occurs (including the initial
one), we merely set trk->fpos_next_frame, and the next
afReadFrames will seek the file there before proceeding.
If ONE_TRACK_ONLY is defined, meaning there can only
be 1 track in the file, we do not need to ever seek
during normal sequential operation, because the file
read module is the only module which ever accesses the
file after _afOpenFile returns. In this case, we do
not need to do the expensive lseek at the beginning of
every AFreadframes call. We need only seek once when the
file is first opened and once when the file is seeked.
At both of these times, we reset the modules. So we
can do the lseek in resetmodules() right after it has
called all of the modules' reset2 methods.
WRITING:
If we are writing, the file needs to be positioned once
before we start writing and it needs to be positioned
after every complete sync operation on the file.
If ONE_TRACK_ONLY is not defined, then there can be
multiple tracks in the file. This assumes space for
the tracks has been preallocated. Thus any call to
AFwriteframes could cause the file pointer to be
put anywhere: we can not rely on the file pointer
tracking only one track in the file, thus we must seek
to the current position in track n whenever we begin
an AFwriteframes on track n. Thus the lseek is done
in AFwriteframes. When we first start, and when a sync
occurs, we merely set trk->fpos_next_frame, and the next
AFwriteframes will seek the file there before proceeding.
If ONE_TRACK_ONLY is defined, meaning there can only
be 1 track in the file, we do not need to ever seek
during normal sequential operation, because the file
write module is the only module which ever accesses
the file after _AFopenfile returns. In this case, we
do not need to do the expensive lseek at the beginning
of every AFwriteframes call. We can do the lseek for
the initial case right here (that's what you see below),
and we can do the lseek for syncs in _AFsyncmodules right
after it has called all of the modules' sync2 methods.
One annoying exceptional case is _AFeditrate, which
can get called at any time. But it saves and restores
the file position at its beginning and end, so it's
no problem.
WHY THE F(*#&@ DON'T YOU JUST HAVE MULTIPLE FILE DESCRIPTORS?
The obviously and blatantly better way to do this would be
to simply open one fd per track and then all the problems
go away! Too bad we offer afOpenFD() in the API, which
makes it impossible for the AF to get more than 1 fd
for the file. afOpenFD() is unfortunately used far
more often than afOpenFile(), so the benefit of doing
the optimization the "right" way in the cases where
afOpenFile() are used are not currently too great.
But one day we will have to phase out afOpenFD().
Too bad, it seemed like such a great idea when we put
it in.
*/
#ifdef ONE_TRACK_ONLY
if (h->access == _AF_WRITE_ACCESS)
{
if (h->seekok && af_fseek(h->fh, track->fpos_next_frame, SEEK_SET) < 0)
{
_af_error(AF_BAD_LSEEK,
"unable to position write ptr at first data frame");
return AF_FAIL;
}
}
#endif
/* Create its rebuffer module. */
if (compunit->needsRebuffer)
{
/* We assume the following for now. */
assert(compunit->nativeSampleFormat == AF_SAMPFMT_TWOSCOMP);
assert(compunit->nativeSampleWidth == 16);
if (h->access == _AF_WRITE_ACCESS)
track->ms.filemod_rebufferinst =
initint2rebufferv2f(chunkframes*track->f.channelCount,
compunit->multiple_of);
else
track->ms.filemod_rebufferinst =
initint2rebufferf2v(chunkframes*track->f.channelCount,
compunit->multiple_of);
track->ms.filemod_rebufferinst.valid = AF_TRUE;
}
else
track->ms.filemod_rebufferinst.valid = AF_FALSE;
/*
These modules should not get freed until the file handle
is destroyed (i.e. the file is closed).
*/
track->ms.filemodinst.free_on_close = AF_TRUE;
track->ms.filemod_rebufferinst.free_on_close = AF_TRUE;
return AF_SUCCEED;
}
/*
addfilereadmods: called once per setup of the modules
for a given AFfilehandle
*/
status addfilereadmods (current_state *current, _Track *track, AFfilehandle h)
{
assert(track->ms.filemodinst.valid);
/* Fail in case code is broken and NDEBUG is defined. */
if (!track->ms.filemodinst.valid)
return AF_FAIL;
addmod(current, track->ms.filemodinst);
if (track->ms.filemod_rebufferinst.valid)
addmod(current, track->ms.filemod_rebufferinst);
return AF_SUCCEED;
}
/*
addfilewritemods is called once per setup of the modules
for a given AFfilehandle.
*/
status addfilewritemods (current_state *current, _Track *track, AFfilehandle h)
{
assert(track->ms.filemodinst.valid);
/* Fail in case code is broken and NDEBUG is defined. */
if (!track->ms.filemodinst.valid)
return(AF_FAIL);
if (track->ms.filemod_rebufferinst.valid)
addmod(current, track->ms.filemod_rebufferinst);
addmod(current, track->ms.filemodinst);
return(AF_SUCCEED);
}
/*
disposefilemods: called once in the lifetime of an AFfilehandle
*/
status disposefilemods (_Track *track)
{
if (track->ms.filemodinst.valid &&
track->ms.filemodinst.mod->free)
(*track->ms.filemodinst.mod->free)(&track->ms.filemodinst);
track->ms.filemodinst.valid = AF_FALSE;
if (track->ms.filemod_rebufferinst.valid &&
track->ms.filemod_rebufferinst.mod->free)
(*track->ms.filemod_rebufferinst.mod->free)(&track->ms.filemod_rebufferinst);
track->ms.filemod_rebufferinst.valid = AF_FALSE;
return AF_SUCCEED;
}
/*
useAP: rate conversion AP decision maker and warner and kludger
*/
bool useAP (double inrate, double outrate, double *inratep, double *outratep)
{
bool instandard =
(inrate==8000 || inrate==11025 || inrate==16000 ||
inrate==22050 || inrate==32000 || inrate==44100 ||
inrate==48000);
bool outstandard =
(outrate==8000 || outrate==11025 || outrate==16000 ||
outrate==22050 || outrate==32000 || outrate==44100 ||
outrate==48000);
bool incodec;
bool outcodec;
incodec = (inrate==_AF_SRATE_CODEC || inrate==(long)_AF_SRATE_CODEC);
outcodec = (outrate==_AF_SRATE_CODEC || outrate==(long)_AF_SRATE_CODEC);
*inratep = inrate;
*outratep = outrate;
if (instandard && outstandard) return AF_TRUE;
if (incodec && outstandard && outrate != 8000.00)
{
_af_error(AF_WARNING_CODEC_RATE,
"WARNING using input rate 8 kHz instead of %.30g Hz "
"to allow high-quality rate conversion",
inrate);
*inratep = 8000.00;
return AF_TRUE;
}
if (instandard && inrate != 8000.00 && outcodec)
{
_af_error(AF_WARNING_CODEC_RATE,
"WARNING using output rate 8 kHz instead of %.30g Hz "
"to allow high-quality rate conversion",
outrate);
*outratep = 8000.00;
return AF_TRUE;
}
if (!instandard && !outstandard)
_af_error(AF_WARNING_RATECVT,
"WARNING using lower quality rate conversion due to "
"rates %.30g and %.30g -- "
"output file may contain audible artifacts",
inrate, outrate);
else if (!instandard)
_af_error(AF_WARNING_RATECVT,
"WARNING using lower quality rate conversion due to "
"input rate %.30g -- "
"output file may contain audible artifacts",
inrate);
else /* !outstandard */
_af_error(AF_WARNING_RATECVT,
"WARNING using lower quality rate conversion due to "
"output rate %.30g -- "
"output file may contain audible artifacts",
outrate);
return AF_FALSE;
}
/*
initrateconvertmods handles the extended-life rate conversion
module and its extended-life rebuffer module called once in the
lifetime of an AFfilehandle.
*/
void initrateconvertmods (bool reading, _Track *track)
{
/* no rate conversion initially */
track->ms.rateconvertinst.valid = AF_FALSE;
track->ms.rateconvert_rebufferinst.valid = AF_FALSE;
}
void disposerateconvertmods (_Track *);
/* XXXmpruett rate conversion is disabled for now */
#if 0
/*
addrateconvertmods: called once per setup of the modules
for a given AFfilehandle
*/
void addrateconvertmods (current_state *current, int nchannels,
double inrate, double outrate,
bool reading, _Track *track)
{
AFframecount inframes, outframes;
/* Check if we are no longer rate converting. */
if (inrate == outrate)
{
disposerateconvertmods(track);
track->ratecvt_filter_params_set = AF_FALSE; /* XXX HACK */
}
else
{
/*
We need new rateconverter if we didn't have one
or if rate has changed or rate conversion params
have changed.
*/
if (!track->ms.rateconvertinst.valid ||
inrate != track->ms.rateconvert_inrate ||
outrate != track->ms.rateconvert_outrate ||
track->ratecvt_filter_params_set /* HACK */)
{
bool usingAP = useAP(inrate, outrate, &inrate, &outrate);
disposerateconvertmods(track);
track->ratecvt_filter_params_set = AF_FALSE; /* HACK */
if (usingAP)
{
track->ms.rateconvertinst = InitAFRateConvert(inrate, outrate,
nchannels,
track->taper, track->dynamic_range,
&inframes, &outframes,
track, reading);
if (!reading)
track->ms.rateconvert_rebufferinst =
initfloatrebufferv2f(inframes*nchannels, AF_FALSE);
else
track->ms.rateconvert_rebufferinst =
initfloatrebufferf2v(outframes*nchannels, AF_FALSE);
track->ms.rateconvertinst.valid = AF_TRUE;
track->ms.rateconvert_rebufferinst.valid = AF_TRUE;
}
else
{
track->ms.rateconvertinst = initpolyratecvt(track,
inrate, outrate,
nchannels, reading);
track->ms.rateconvertinst.valid = AF_TRUE;
track->ms.rateconvert_rebufferinst.valid = AF_FALSE;
}
track->ms.rateconvert_inrate = inrate;
track->ms.rateconvert_outrate = outrate;
track->ms.rateconvertinst.free_on_close = AF_TRUE;
track->ms.rateconvert_rebufferinst.free_on_close = AF_TRUE;
}
/* Add the rate conversion modules. */
if (!reading && track->ms.rateconvert_rebufferinst.valid)
addmod(current, track->ms.rateconvert_rebufferinst);
addmod(current, track->ms.rateconvertinst);
if (reading && track->ms.rateconvert_rebufferinst.valid)
addmod(current, track->ms.rateconvert_rebufferinst);
}
}
/*
disposerateconvertmods is called once in the lifetime of an
AFfilehandle.
*/
void disposerateconvertmods (_Track *track)
{
/*
Neither module is necessarily valid--there could have been
an error, or the modules could possibly never have been set up.
*/
if (track->ms.rateconvertinst.valid &&
track->ms.rateconvertinst.mod->free)
{
(*track->ms.rateconvertinst.mod->free)
(&track->ms.rateconvertinst);
}
track->ms.rateconvertinst.valid = AF_FALSE;
if (track->ms.rateconvert_rebufferinst.valid &&
track->ms.rateconvert_rebufferinst.mod->free)
{
(*track->ms.rateconvert_rebufferinst.mod->free)
(&track->ms.rateconvert_rebufferinst);
}
track->ms.rateconvert_rebufferinst.valid = AF_FALSE;
}
#endif /* XXXmpruett rate conversion is disabled for now */
/* -------------------------------------------------------------- */
/* The stuff in this section is used by arrangemodules(). */
_AFmodule *unsigned2signed[5] =
{
NULL,
&unsigned2signed1, &unsigned2signed2,
&unsigned2signed3, &unsigned2signed4
};
_AFmodule *signed2unsigned[5] =
{
NULL,
&signed2unsigned1, &signed2unsigned2,
&signed2unsigned3, &signed2unsigned4
};
_AFmodule *swapbytes[9] =
{
NULL, NULL, &swap2, &swap3, &swap4,
NULL, NULL, NULL, &swap8
};
/* don't forget int24_fmt is really 24 bits right-justified in 32 bits */
typedef enum format_code
{
int8_fmt,
int16_fmt,
int24_fmt,
int32_fmt,
float_fmt,
double_fmt
} format_code;
#define isinteger(fc) ((fc) <= int32_fmt)
#define isfloating(fc) ((fc) >= float_fmt)
/*
get_format_code
*/
format_code get_format_code (_AudioFormat *fmt)
{
if (fmt->sampleFormat == AF_SAMPFMT_FLOAT)
return float_fmt;
if (fmt->sampleFormat == AF_SAMPFMT_DOUBLE)
return double_fmt;
if (fmt->sampleFormat == AF_SAMPFMT_TWOSCOMP ||
fmt->sampleFormat == AF_SAMPFMT_UNSIGNED)
{
switch (_af_format_sample_size_uncompressed(fmt, AF_FALSE))
{
case 1: return int8_fmt;
case 2: return int16_fmt;
case 3: return int24_fmt;
case 4: return int32_fmt;
}
}
/* NOTREACHED */
assert(0);
return -1;
}
_AFmodule *to_flt[6] =
{
&int2float1, &int2float2, &int2float3, &int2float4,
NULL, &double2float
};
_AFmodule *to_dbl[6] =
{
&int2double1, &int2double2, &int2double3, &int2double4,
&float2double, NULL
};
_AFmodule *clip[6] =
{
&clip1, &clip2, &clip3, &clip4,
&clipfloat, &clipdouble
};
_AFmodule *channelchanges[6] =
{
&channelchange1, &channelchange2, &channelchange3, &channelchange4,
&channelchangefloat, &channelchangedouble
};
/* indices are of type format_code: matrix[infmtcode][outfmtcode] */
_AFmodule *convertmatrix[6][6] =
{
/* TO:
{
int8_fmt, int16_fmt,
int24_fmt, int32_fmt,
float_fmt, double_fmt
}
*/
/* FROM int8_fmt */
{
NULL, &int1_2,
&int1_3, &int1_4,
&int2float1, &int2double1
},
/* FROM int16_fmt */
{
&int2_1, NULL,
&int2_3, &int2_4,
&int2float2, &int2double2
},
/* FROM int24_fmt */
{
&int3_1, &int3_2,
NULL, &int3_4,
&int2float3, &int2double3
},
/* FROM int32_fmt */
{
&int4_1, &int4_2,
&int4_3, NULL,
&int2float4, &int2double4
},
/* FROM float_fmt */
{
&float2int1_clip, &float2int2_clip,
&float2int3_clip, &float2int4_clip,
NULL, &float2double
},
/* FROM double_fmt */
{
&double2int1_clip, &double2int2_clip,
&double2int3_clip, &double2int4_clip,
&double2float, NULL
}
};
_PCMInfo *intmappings[6] =
{
&_af_default_signed_integer_pcm_mappings[1],
&_af_default_signed_integer_pcm_mappings[2],
&_af_default_signed_integer_pcm_mappings[3],
&_af_default_signed_integer_pcm_mappings[4],
AF_NULL, AF_NULL
};
/*
trivial_int_clip
*/
bool trivial_int_clip (_AudioFormat *f, format_code code)
{
return (intmappings[code] != NULL &&
f->pcm.minClip == intmappings[code]->minClip &&
f->pcm.maxClip == intmappings[code]->maxClip);
}
/*
trivial_int_mapping
*/
bool trivial_int_mapping (_AudioFormat *f, format_code code)
{
return (intmappings[code] != NULL &&
f->pcm.slope == intmappings[code]->slope &&
f->pcm.intercept == intmappings[code]->intercept);
}
/*
arrangemodules decides which modules to use and creates instances
of them.
*/
status arrangemodules (_AFfilehandle *h, _Track *track)
{
bool reading = (h->access == _AF_READ_ACCESS);
current_state current;
bool rateconverting, transforming;
bool already_clipped_output, already_transformed_output;
int insampbytes, outsampbytes;
int chans;
format_code infc, outfc;
/*
in and out are the formats at the start and end of the
chain of modules, respectively.
*/
_AudioFormat in, out;
/* in==FILE, out==virtual (user) */
if (reading)
{
in = track->f;
out = track->v;
}
/* in==virtual (user), out==FILE */
else
{
in = track->v;
out = track->f;
}
infc = get_format_code(&in);
outfc = get_format_code(&out);
/* flags */
rateconverting = (in.sampleRate != out.sampleRate);
/*
throughout routine:
current.modinst points to current module
current.inchunk points to current in chunk, always outchunk-1
current.outchunk points to current out chunk
The addmod() function does most of the work. It calls the
"describe" module function, during which a module looks
at inc->f and writes the format it will output in outc->f.
*/
current.modinst = track->ms.module;
current.inchunk = track->ms.chunk;
current.outchunk = track->ms.chunk + 1;
current.inchunk->f = in;
/*
max # of modules that could be needed together
may need to change this if you change this function
*/
#define MAX_MODULES 17
/* Actually arrange the modules. Call addmod() to add one. */
/* Add file reader and possibly a decompressor. */
if (reading)
if (AF_FAIL == addfilereadmods(¤t, track, h))
return AF_FAIL;
/* Make data native-endian. */
if (in.byteOrder != _AF_BYTEORDER_NATIVE)
{
int bytes_per_samp = _af_format_sample_size_uncompressed(&in, !reading);
if (bytes_per_samp > 1 &&
in.compressionType == AF_COMPRESSION_NONE)
{
assert(swapbytes[bytes_per_samp]);
addmod(¤t, _AFnewmodinst(swapbytes[bytes_per_samp]));
}
else
in.byteOrder = _AF_BYTEORDER_NATIVE;
}
/* Handle nasty 3-byte input cases. */
insampbytes = _af_format_sample_size_uncompressed(&in, AF_FALSE);
if (isinteger(infc) && insampbytes == 3)
{
if (reading || in.compressionType != AF_COMPRESSION_NONE)
{
/*
We're reading 3-byte ints from a file.
At this point stretch them to 4-byte ints
by sign-extending or adding a zero-valued
most significant byte. We could also
be reading/writing 3-byte samples output
from a decompressor.
*/
if (in.sampleFormat == AF_SAMPFMT_UNSIGNED)
addmod(¤t, _AFnewmodinst(&real_char3_to_uchar3));
else
addmod(¤t, _AFnewmodinst(&real_char3_to_schar3));
}
else /* writing, non-compressed */
{
/*
We're processing 3-byte ints from the
user, which come in as sign-extended
4-byte quantities. How convenient:
this is what we want.
*/
}
}
/* Make data signed. */
if (in.sampleFormat == AF_SAMPFMT_UNSIGNED)
{
addmod(¤t, _AFnewmodinst(unsigned2signed[insampbytes]));
}
/* Standardize pcm mapping of "in" and "out". */
/*
Since they are used to compute transformations in the
inner section of this routine (inside of sign conversion),
we need in.pcm and out.pcm in terms of AF_SAMPFMT_TWOSCOMP
numbers.
*/
in.pcm = current.inchunk->f.pcm; /* "in" is easy */
if (out.sampleFormat == AF_SAMPFMT_UNSIGNED) /* "out": undo the unsigned shift */
{
double shift = intmappings[outfc]->minClip;
out.pcm.intercept += shift;
out.pcm.minClip += shift;
out.pcm.maxClip += shift;
}
/* ------ CLIP user's input samples if necessary */
if (in.pcm.minClip < in.pcm.maxClip && !trivial_int_clip(&in, infc))
addmod(¤t, initpcmmod(clip[infc], AF_NULL, &in.pcm));
/*
At this point, we assume we can have doubles, floats,
and 1-, 2-, and 4-byte signed integers on the input and
on the output (or 4-byte integers with 24 significant
(low) bits, int24_fmt).
Now we handle rate conversion and pcm transformation.
*/
/* If rate conversion will happen, we must have floats. */
/*
This may result in loss of precision. This bug must be
fixed eventually.
*/
if (rateconverting && infc != float_fmt)
{
addmod(¤t, _AFnewmodinst(to_flt[infc]));
infc = float_fmt;
}
/*
We must make sure the output samples will get clipped
to SOMETHING reasonable if we are rateconverting.
The user cannot possibly expect to need to clip values
just because rate conversion is on.
*/
if (out.pcm.minClip >= out.pcm.maxClip && rateconverting)
{
out.pcm.minClip = out.pcm.intercept - out.pcm.slope;
out.pcm.maxClip = out.pcm.intercept + out.pcm.slope;
}
already_clipped_output = AF_FALSE;
already_transformed_output = AF_FALSE;
/*
We need to perform a transformation (in floating point)
if the input and output PCM mappings are different.
The only exceptions are the trivial integer conversions
(i.e., full-range integers of one # of bytes to full-range
integers to another # of bytes).
*/
transforming = (in.pcm.slope != out.pcm.slope ||
in.pcm.intercept != out.pcm.intercept) &&
!(trivial_int_mapping(&in, infc) &&
trivial_int_mapping(&out,outfc));
/*
If we have ints on input and the user is performing a
change of mapping other than a trivial one, we must go
to floats or doubles.
*/
if (isinteger(infc) && transforming)
{
/*
Use doubles if either the in or out format has
that kind of precision.
*/
if (infc == int32_fmt ||
outfc == double_fmt || outfc == int32_fmt)
{
addmod(¤t, _AFnewmodinst(to_dbl[infc]));
infc = double_fmt;
}
else
{
addmod(¤t, _AFnewmodinst(to_flt[infc]));
infc = float_fmt;
}
}
DEBG(printf("arrangemodules in="); _af_print_audioformat(&in););
DEBG(printf("arrangemodules out="); _af_print_audioformat(&out););
DEBG(printf("arrangemodules transforming=%d\n", transforming));
DEBG(printf("arrangemodules infc=%d outfc=%d\n", infc, outfc));
/*
invariant:
At this point, if infc is an integer format, then we are
not rate converting, nor are we perfoming any change of
mapping other than possibly a trivial int->int conversion.
*/
/* ----- convert format infc to format outfc */
/* change channels if appropriate now */
if (in.channelCount != out.channelCount &&
(infc > outfc || (infc==outfc && out.channelCount < in.channelCount)))
{
addmod(¤t,
initchannelchange(channelchanges[infc],
track->channelMatrix, &in.pcm,
in.channelCount, out.channelCount,
reading));
chans = out.channelCount;
}
else
chans = in.channelCount;
/* Transform floats if appropriate now. */
if (transforming &&
infc==double_fmt && isfloating(outfc))
{
addmod(¤t, initpcmmod(&doubletransform, &in.pcm, &out.pcm));
}
#if 0 /* XXXmpruett */
/*
Handle rate conversion (will do the right thing if
not rate converting).
*/
addrateconvertmods(¤t, chans, in.sampleRate, out.sampleRate, reading, track);
#endif
/* Add format conversion, if needed */
if (convertmatrix[infc][outfc])
{
/*
for float/double -> int conversions, the module
we use here also does the transformation and
clipping.
We use initpcmmod() in any case because it is harmless
for the other modules in convertmatrix[][].
*/
if (isfloating(infc) && isinteger(outfc)) /* "float"->"int" */
{
already_clipped_output = AF_TRUE;
already_transformed_output = AF_TRUE;
}
addmod(¤t, initpcmmod(convertmatrix[infc][outfc],
&in.pcm, &out.pcm));
}
/* Transform floats if appropriate now. */
if (transforming && !already_transformed_output && infc != double_fmt)
{
if (outfc==double_fmt)
addmod(¤t, initpcmmod(&doubletransform,
&in.pcm, &out.pcm));
else if (outfc==float_fmt)
addmod(¤t, initpcmmod(&floattransform,
&in.pcm, &out.pcm));
}
/* Change channels if appropriate now. */
if (in.channelCount != out.channelCount &&
(outfc > infc || (infc==outfc && in.channelCount < out.channelCount)))
{
addmod(¤t,
initchannelchange(channelchanges[outfc],
track->channelMatrix, &out.pcm,
in.channelCount, out.channelCount,
reading));
}
/* ------ CLIP user's output samples if needed */
if (!already_clipped_output)
{
if (out.pcm.minClip < out.pcm.maxClip &&
!trivial_int_clip(&out, outfc))
{
addmod(¤t, initpcmmod(clip[outfc], NULL, &out.pcm));
}
}
/* Make data unsigned if neccessary. */
outsampbytes = _af_format_sample_size_uncompressed(&out, AF_FALSE);
if (out.sampleFormat == AF_SAMPFMT_UNSIGNED)
addmod(¤t, _AFnewmodinst(signed2unsigned[outsampbytes]));
/* Handle nasty 3-byte output cases. */
if (isinteger(outfc) && outsampbytes == 3)
{
if (!reading || out.compressionType != AF_COMPRESSION_NONE)
{
/*
We're writing 3-byte ints into a file.
We have 4-byte ints. Squish them to
3 by truncating the high byte off.
we could also be reading/writing ints
into a compressor. note this works for
signed and unsigned, and has to.
*/
addmod(¤t, _AFnewmodinst(&char3_to_real_char3));
}
else /* reading, not compressed */
{
/*
We're reading 3-byte ints into the
user's buffer.
The user expects
1. 4-byte sign-extended ints (3 bytes
sign extended in 4 bytes) or
2. 4-byte unsigned ints (3 bytes in 4 bytes).
How convenient: this is just what we have.
*/
}
}
if (out.byteOrder != _AF_BYTEORDER_NATIVE)
{
int bytes_per_samp = _af_format_sample_size_uncompressed(&out, reading);
if (bytes_per_samp > 1 && out.compressionType == AF_COMPRESSION_NONE)
{
assert(swapbytes[bytes_per_samp]);
addmod(¤t, _AFnewmodinst(swapbytes[bytes_per_samp]));
}
}
/* Add file writer, possibly a compressor. */
if (!reading)
if (AF_FAIL == addfilewritemods(¤t, track, h))
return(AF_FAIL);
/* Now all modules are arranged! */
track->ms.nmodules = current.modinst - track->ms.module;
#ifdef UNLIMITED_CHUNK_NVFRAMES
/*
OPTIMIZATION: normally, when we set up the modules, AFreadframes
and AFwriteframes must pull and push chunks of size at most
_AF_ATOMIC_NVFRAMES.
For the simplest configurations of modules (1 module, no
compression), no buffering at all needs to be done by the
module system. In these cases, afReadFrames/afWriteFrames
can pull/push as many virtual frames as they want
in one call. This flag tells tells afReadFrames and
afWriteFrames whether they can do so.
Note that if this flag is set, file modules cannot rely
on the intermediate working buffer which _AFsetupmodules
usually allocates for them in their input or output chunk
(for reading or writing, respectively). This is why if
we are reading/writing compressed data, this optimization
is turned off.
There are warnings to this effect in the pcm
(uncompressed) file read/write module. If you want to
apply this optimization to other types, be sure to put
similar warnings in the code.
*/
if (track->ms.nmodules == 1 &&
track->v.compressionType == AF_COMPRESSION_NONE &&
track->f.compressionType == AF_COMPRESSION_NONE)
track->ms.mustuseatomicnvframes = AF_FALSE;
else
track->ms.mustuseatomicnvframes = AF_TRUE;
#else
track->ms.mustuseatomicnvframes = AF_TRUE;
#endif
return AF_SUCCEED;
}
/*
disposemodules will free old buffers and free old modules, except
those marked with free_on_close.
The modules existing before we dispose them could be:
1. none (we may have only called _AFinitmodules and not _AFsetupmodules)
2. some invalid PARTIALLY ALLOCATED ones (e.g. the last _AFsetupmodules
had an error) or
3. a perfectly valid set of modules.
disposemodules will deal with all three cases.
*/
void disposemodules (_Track *track)
{
if (track->ms.module)
{
int i;
for (i=0; i < MAX_MODULES; i++)
{
_AFmoduleinst *mod = &track->ms.module[i];
#ifdef AF_DEBUG
if (!mod->valid && i < track->ms.nmodules)
printf("disposemodules: WARNING in-range invalid module found '%s'\n", mod->mod->name);
#endif
if (mod->valid && !mod->free_on_close && mod->mod->free)
{
(*mod->mod->free)(mod);
mod->valid = AF_FALSE;
}
}
free(track->ms.module);
track->ms.module = AF_NULL;
}
track->ms.nmodules = 0;
if (track->ms.chunk)
{
free(track->ms.chunk);
track->ms.chunk = AF_NULL;
}
if (track->ms.buffer)
{
int i;
for (i=0; i < (MAX_MODULES+1); i++)
{
if (track->ms.buffer[i] != AF_NULL)
{
free(track->ms.buffer[i]);
track->ms.buffer[i] = AF_NULL;
}
}
free(track->ms.buffer);
track->ms.buffer = AF_NULL;
}
}
/*
resetmodules: see advanced section in README.modules for more info
*/
status resetmodules (_AFfilehandle *h, _Track *track)
{
int i;
/*
We should already have called _AFsetupmodules.
(Actually this is called from the end of _AFsetupmodules
but whatever).
*/
assert(!track->ms.modulesdirty);
/* Assume all is well with track. */
track->filemodhappy = AF_TRUE;
CHNK(printf("resetmodules running reset1 routines\n"));
/* Reset all modules. */
for (i=track->ms.nmodules-1; i >= 0; i--)
{
/* reset1 */
if (track->ms.module[i].mod->reset1 != AF_NULL)
(*track->ms.module[i].mod->reset1)(&track->ms.module[i]);
}
/* Clear out frames2ignore here; the modules will increment it. */
track->frames2ignore = 0;
if (!track->filemodhappy)
return AF_FAIL;
CHNK(printf("resetmodules running reset2 routines\n"));
for (i=0; i < track->ms.nmodules; i++)
{
/* reset2 */
if (track->ms.module[i].mod->reset2 != AF_NULL)
(*track->ms.module[i].mod->reset2)(&track->ms.module[i]);
}
CHNK(printf("resetmodules completed\n"));
if (!track->filemodhappy)
return AF_FAIL;
#ifdef ONE_TRACK_ONLY
/*
For an explanation of this, see the comment in
initfilemods which explains how and when the file is
lseek'ed.
*/
if (h->seekok)
if (lseek(h->fd, track->fpos_next_frame, SEEK_SET) < 0)
{
_af_error(AF_BAD_LSEEK,
"unable to position read pointer at next data frame");
return AF_FAIL;
}
#endif
return AF_SUCCEED;
}
/*
_AFsyncmodules
*/
status _AFsyncmodules (AFfilehandle h, _Track *track)
{
int i;
/* We should already have called _AFsetupmodules. */
assert(!track->ms.modulesdirty);
/* Assume all is well with track. */
track->filemodhappy = AF_TRUE;
CHNK(printf("_AFsyncmodules running sync1 routines\n"));
/* Sync all modules. */
for(i=track->ms.nmodules-1; i >= 0; i-- )
{
/* sync1 */
if (AF_NULL != track->ms.module[i].mod->sync1)
(*track->ms.module[i].mod->sync1)(&track->ms.module[i]);
}
if (!track->filemodhappy)
return AF_FAIL;
CHNK(printf("_AFsyncmodules running sync2 routines\n"));
for (i=0; i < track->ms.nmodules; i++)
{
/* sync2 */
if (AF_NULL != track->ms.module[i].mod->sync2)
(*track->ms.module[i].mod->sync2)(&track->ms.module[i]);
}
CHNK(printf("_AFsyncmodules completed\n"));
if (!track->filemodhappy)
return AF_FAIL;
#ifdef ONE_TRACK_ONLY
/*
For an explanation of this, see the comment in
initfilemods which explains how and when the file is
lseek'ed.
*/
if (h->seekok)
if (lseek( h->fd, track->fpos_next_frame, SEEK_SET) < 0 )
{
_af_error(AF_BAD_LSEEK,
"unable to position write ptr at next data frame");
return(AF_FAIL);
}
#endif
return AF_SUCCEED;
}
/*
_AFsetupmodules:
- frees any old modules, chunks, and buffers
- looks at the input and output format and sets up a whole new
set of input and output modules (using arrangemodules())
- assigns those modules chunks
- allocates buffers and assigns the buffers to the chunks
- initializes various track fields pertaining to the module system
It returns AF_FAIL on any kind of error.
It sets modulesdirty to AF_FALSE if it was able to clean the
modules (although an error still could have occurred after
cleaning them).
*/
status _AFsetupmodules (AFfilehandle h, _Track *track)
{
_AFmoduleinst *modules;
_AFchunk *chunks;
void **buffers;
int maxbufsize, bufsize, i;
double rateratiof2v, fframepos;
/*
The purpose of this function is to "clean" the modules:
* All of the fields in trk->ms are completely set
and valid.
* track->totalvframes and track->next[fv]frame are set
and valid and trk->modulesdirty will be set to AF_FALSE
if this function succeeds.
This function also resets the modules on files open for read.
it will return AF_FAIL if either cleaning the modules fails,
or this reset fails.
The comments will tell you which part does what.
*/
/*
NOTE: we cannot trust any value in track->ms until we
have called disposemodules(), at which time things are
cleared to reasonable "zero" values.
It is possible for track->ms to be in an illegal state
at this point, if the last _AFsetupmodules failed with
an error.
We can trust track->totalvframes and track->next[fv]frame
because they are only modified after successfully building
the modules.
*/
/*
Disallow compression in virtual format for now.
*/
if (track->v.compressionType != AF_COMPRESSION_NONE)
{
_af_error(AF_BAD_NOT_IMPLEMENTED,
"library does not support compression in virtual format yet");
return AF_FAIL;
}
/*
Check that virtual compression parameters are ok.
*/
{
int idx = _af_compression_index_from_id(track->v.compressionType);
if ((*_af_compression[idx].fmtok)(&track->v) == AF_FALSE)
{
return AF_FAIL;
}
}
/*
track->nextvframe and track->nextfframe:
At this point, only track->nextvframe contains useful
information, since track->nextfframe may be swayed by
currently buffered frames.
Also track->nextvframe is currently in the scale of the
old sampling rate, not the new one we are setting up.
So at this point we remember where we are in the file
(in floating point) in terms of the file sampling rate.
We will use this later in this function to set both
track->nextfframe (for reading) and track->nextvframe
(for reading and writing).
We must be careful to use the old rates, not the ones
in track->{f,v}.
*/
/* If modules have been set up at all */
if (track->ms.old_v_rate > 0)
{
assert(track->ms.old_f_rate > 0);
rateratiof2v = track->ms.old_f_rate / track->ms.old_v_rate;
fframepos = track->nextvframe * rateratiof2v;
}
else
/* We start at frame zero. */
fframepos = 0;
/*
Dispose the existing modules (except extended-life ones).
See the function for info on what the module state could
be at this time.
*/
disposemodules(track);
/*
Here we allocate the highest number of module instances
(and chunks) chained together we could possibly need.
This is how the chunks are used:
module[n]'s input chunk is chunk[n]
module[n]'s output chunk is chunk[n+1]
chunk[n]'s buffer, if it is not the user's buffer, is buffer[n].
For reading chunk[0] is not usually used.
For writing chunk[nmodules] is not usually used.
We allocate a buffer for chunk[0] on reading and
chunk[nmodules] when writing because the file reading
or file writing module, if it does compression or
decompression, may need extra space in which to place
the result of its processing before reading or writing it.
Also note that chunk[0].f and chunk[nmodules].f are used in
arrangemodules().
*/
modules = _af_malloc(sizeof (_AFmoduleinst) * MAX_MODULES);
if (modules == AF_NULL)
return AF_FAIL;
for (i=0; i < MAX_MODULES; i++)
modules[i].valid = AF_FALSE;
chunks = _af_malloc(sizeof (_AFchunk) * (MAX_MODULES+1));
if (chunks == AF_NULL)
return AF_FAIL;
buffers = _af_malloc(sizeof (void *) * (MAX_MODULES+1));
if (buffers == AF_NULL)
return AF_FAIL;
/*
It is very important to initialize each buffers[i] to NULL;
dispose frees them all if !NULL.
*/
for (i=0; i < (MAX_MODULES+1); i++)
buffers[i] = AF_NULL;
track->ms.module = modules;
/*
nmodules is a bogus value here, set just for sanity
(in case of broken code).
*/
track->ms.nmodules = 0;
track->ms.chunk = chunks;
track->ms.buffer = buffers;
/*
Figure out the best modules to use to convert the
data and initialize instances of those modules.
Fills "track->ms.module" and most of "track->ms.chunk"
arrays (all but the buffers) as it goes. Sets
"track->ms.nmodules" As a side benefit, this function
also leaves information about the data format at each
stage in the "f" field of each chunk.
*/
if (arrangemodules(h, track) == AF_FAIL)
{
/*
At this point the modules are in an incompletely
initialized and probably illegal state. nmodules
could be meaningful or not. Things are nasty.
But as long as any API call that uses the
modules calls _AFsetupmodules() first (which
then calls disposemodules(), which can handle
this nastiness), we can restore the modules to
a sane initial state and things will be ok.
*/
return AF_FAIL;
}
/*
At this point modules and nmodules are almost completely
filled in (modules aren't actually connected to one
another), but buffer[n] and chunk[n].buf are still in
a null state.
track->totalvframes and track->next[fv]frame have not yet been
set to a valid state.
*/
/*
Now go through the modules:
1. Connect up the source/sink fields properly.
2. Use the information left in the _AudioFormat field
of each chunk by setupmodules() along with the
"max_pull"/"max_push" module function to figure
out the biggest buffer size that could be needed.
*/
/* filemod reports error here */
track->filemodhappy = AF_TRUE;
maxbufsize = 0;
if (h->access == _AF_READ_ACCESS)
{
track->ms.chunk[track->ms.nmodules].nframes = _AF_ATOMIC_NVFRAMES;
for (i=track->ms.nmodules-1; i >= 0; i--)
{
_AFchunk *inc = &track->ms.chunk[i];
_AFchunk *outc = &track->ms.chunk[i+1];
/* check bufsize needed for current output chunk */
bufsize = outc->nframes * _af_format_frame_size(&outc->f, AF_TRUE);
if (bufsize > maxbufsize)
maxbufsize = bufsize;
if (i != 0)
{
/* Connect source pointer for this module. */
track->ms.module[i].u.pull.source = &track->ms.module[i-1];
}
/*
Determine inc->nframes from outc->nframes.
If the max_pull function is present, we use it,
otherwise we assume module does no weird
buffering or rate conversion.
*/
if (track->ms.module[i].mod->max_pull)
(*track->ms.module[i].mod->max_pull)(&track->ms.module[i]);
else
inc->nframes = outc->nframes;
}
if (!track->filemodhappy)
return AF_FAIL;
/*
Check bufsize needed for filemod's input chunk
(intermediate buffer) based on an uncompressed
(output chunk) framesize.
*/
{
_AFmoduleinst *filemod = &track->ms.module[0];
bufsize = filemod->inc->nframes *
_af_format_frame_size(&filemod->outc->f, AF_TRUE);
if (bufsize > maxbufsize)
maxbufsize = bufsize;
}
}
else
{
track->ms.chunk[0].nframes = _AF_ATOMIC_NVFRAMES;
for (i=0; i < track->ms.nmodules; i++)
{
_AFchunk *inc = &track->ms.chunk[i];
_AFchunk *outc = &track->ms.chunk[i+1];
/* Check bufsize needed for current input chunk. */
bufsize = inc->nframes * _af_format_frame_size(&inc->f, AF_TRUE);
if (bufsize > maxbufsize)
maxbufsize = bufsize;
if (i != track->ms.nmodules-1)
{
/* Connect sink pointer. */
track->ms.module[i].u.push.sink = &track->ms.module[i+1];
}
/*
Determine outc->nframes from inc->nframes.
If the max_push function is present, we use it,
otherwise we assume module does no weird
buffering or rate conversion.
*/
if (track->ms.module[i].mod->max_push)
(*track->ms.module[i].mod->max_push)(&track->ms.module[i]);
else
outc->nframes = inc->nframes;
}
if (!track->filemodhappy)
return AF_FAIL;
/*
Check bufsize needed for filemod's output chunk
(intermediate buffer) based on an uncompressed (input
chunk) framesize.
*/
{
_AFmoduleinst *filemod = &track->ms.module[track->ms.nmodules-1];
bufsize = filemod->outc->nframes *
_af_format_frame_size(&filemod->inc->f, AF_TRUE);
if (bufsize > maxbufsize)
maxbufsize = bufsize;
}
}
/*
At this point everything is totally set up with the
modules except that the chunk buffers have not been
allocated, and thus buffer[n] and chunk[n].buf have
not been set. But now we know how big they should be
(maxbufsize).
track->totalvframes and track->next[fv]frame have not
yet been set to a valid state.
*/
DEBG(printf("_AFsetupmodules: maxbufsize=%d\n", maxbufsize));
/*
One of these will get overwritten to point to user's
buffer. The other one will be allocated below (for file
read/write module).
*/
track->ms.chunk[track->ms.nmodules].buf = AF_NULL;
track->ms.chunk[0].buf = AF_NULL;
/*
One of these will be allocated for the file read/write
module The other will be completely unused.
*/
track->ms.buffer[track->ms.nmodules] = AF_NULL;
track->ms.buffer[0] = AF_NULL;
/*
Now that we know how big buffers have to be, allocate
buffers and assign them to the module instances.
Note that track->ms.chunk[nmodules].buf (reading) or
track->ms.chunk[0].buf (writing) will get overwritten
in _AFreadframes or _AFwriteframes to point to the
user's buffer.
We allocate a buffer for track->ms.chunk[0].buf (reading)
or track->ms.chunk[nmodules].buf (writing) not because
it is needed for the modules to work, but as a working
buffer for the file reading / file writing modules.
Also note that some modules may change their inc->buf or
outc->buf to point to something internal to the module
before calling their source or sink.
So module code must be careful not to assume that a buffer
address will not change. Only for chunk[nmodules]
(reading) or chunk[0] (writing) is such trickery
disallowed.
*/
if (h->access == _AF_READ_ACCESS)
for (i=track->ms.nmodules-1; i >= 0; i--)
{
if ((track->ms.buffer[i] = _af_malloc(maxbufsize)) == AF_NULL)
return AF_FAIL;
track->ms.chunk[i].buf = track->ms.buffer[i];
}
else
for (i=1; i <= track->ms.nmodules; i++)
{
if ((track->ms.buffer[i] = _af_malloc(maxbufsize)) == AF_NULL)
return AF_FAIL;
track->ms.chunk[i].buf = track->ms.buffer[i];
}
/*
Hooray! The modules are now in a completely valid state.
But we can't set track->ms.modulesdirty to AF_FALSE yet...
track->totalvframes and track->next[fv]frame have not yet been
set to a valid state.
*/
if (h->access == _AF_READ_ACCESS)
{
/*
Set total number of virtual frames based on new rate.
*/
if (track->totalfframes == -1)
track->totalvframes = -1;
else
track->totalvframes = track->totalfframes *
(track->v.sampleRate / track->f.sampleRate);
/*
track->nextvframe and track->nextfframe:
Currently our only indication of where we were
in the file is the variable fframepos, which
contains (in floating point) our offset in file
frames based on the old track->nextvframe.
Now we get as close as we can to that original
position, given the new sampling rate.
*/
track->nextfframe = (AFframecount) fframepos;
track->nextvframe = (AFframecount) (fframepos * (track->v.sampleRate / track->f.sampleRate));
/*
Now we can say the module system is in a
clean state. Any errors we get from here on
are reported but not critical.
*/
track->ms.modulesdirty = AF_FALSE;
/* Set up for next time. */
track->ms.old_f_rate = track->f.sampleRate;
track->ms.old_v_rate = track->v.sampleRate;
/*
Now we reset all the modules.
If we are here because the user did afSeekFrame,
the actual seek will be performed here.
Otherwise this reset will set things up so that
we are at the same file offset we were at before
(or as close as possible given a change in
rate conversion).
*/
/* Report error, but we're still clean. */
if (AF_SUCCEED != resetmodules(h, track))
return AF_FAIL;
}
/* Handle the case of _AF_WRITE_ACCESS. */
else
{
/*
Don't mess with track->nextfframe or
track->totalfframes. Scale virtual frame position
relative to old virtual position.
*/
track->nextvframe = track->totalvframes =
(AFframecount) (fframepos * (track->v.sampleRate / track->f.sampleRate));
/*
Now we can say the module system is in a
clean state. Any errors we get from here on
are reported but not critical.
*/
track->ms.modulesdirty = AF_FALSE;
/* Set up for next time. */
track->ms.old_f_rate = track->f.sampleRate;
track->ms.old_v_rate = track->v.sampleRate;
}
DEBG(_af_print_filehandle(h));
#ifdef DEBUG
for (i=track->ms.nmodules-1; i >= 0; i--)
{
_AFmoduleinst *inst = &track->ms.module[i];
}
{
/* Print format summary. */
printf("%s ->\n", (h->access == _AF_READ_ACCESS) ? "file" : "user");
for (i=0; i < track->ms.nmodules; i++)
{
_AFmoduleinst *inst = &track->ms.module[i];
_af_print_audioformat(&inst->inc->f);
printf(" -> %s(%d) ->\n", inst->mod->name, i);
}
_af_print_audioformat(&track->ms.chunk[track->ms.nmodules].f);
printf(" -> %s\n", (h->access != _AF_READ_ACCESS) ? "file" : "user");
}
#endif
/*
If we get here, then not only are the modules clean, but
whatever we did after the modules became clean succeeded.
So we gloat about our success.
*/
return AF_SUCCEED;
}
/*
_AFinitmodules: this routine sets the initial value of the module-
related fields of the track when the track is first created.
It also initializes the file read or file write modules.
See README.modules for info on this.
Set "modulesdirty" flag on each track, so that the first
read/write/seek will set up the modules.
*/
status _AFinitmodules (AFfilehandle h, _Track *track)
{
track->channelMatrix = NULL;
/* HACK: see private.h for a description of this hack */
track->taper = 10;
track->dynamic_range = 100;
track->ratecvt_filter_params_set = AF_TRUE;
track->ms.nmodules = 0;
track->ms.module = NULL;
track->ms.chunk = NULL;
track->ms.buffer = NULL;
track->ms.modulesdirty = AF_TRUE;
track->ms.filemodinst.valid = AF_FALSE;
track->ms.filemod_rebufferinst.valid = AF_FALSE;
track->ms.rateconvertinst.valid = AF_FALSE;
track->ms.rateconvert_rebufferinst.valid = AF_FALSE;
/* bogus value in case of bad code */
track->ms.mustuseatomicnvframes = AF_TRUE;
/* old_f_rate and old_v_rate MUST be set to <= 0 here. */
track->ms.old_f_rate = -1;
track->ms.old_v_rate = -1;
/*
Initialize extended-life file read or file write modules.
*/
if (AF_FAIL == initfilemods(track, h))
return AF_FAIL;
/*
Initialize extended-life rate convert modules (to NULL).
*/
initrateconvertmods(h->access == _AF_READ_ACCESS, track);
/*
NOTE: Only now that we have initialized filemods is
track->totalfframes guaranteed to be ready. (The unit
cannot always tell how many frames are in the file.)
*/
/* totalfframes could be -1. */
track->totalvframes = track->totalfframes;
track->nextvframe = 0;
track->frames2ignore = 0;
return AF_SUCCEED;
}
/*
_AFfreemodules:
called once when filehandle is being freed
opposite of initmodules
free all modules, even the active ones
*/
void _AFfreemodules (_Track *track)
{
disposemodules(track);
disposefilemods(track);
#if 0 /* XXXmpruett rate conversion is deactivated for now */
disposerateconvertmods(track);
#endif
}