File: _core.py

package info (click to toggle)
python-pyo 1.0.6-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 52,332 kB
  • sloc: python: 135,133; ansic: 127,822; javascript: 16,116; sh: 395; makefile: 388; cpp: 242
file content (3675 lines) | stat: -rw-r--r-- 119,982 bytes parent folder | download | duplicates (2)
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
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
# encoding: utf-8
"""
This module defines the base classes for all objects in the library.

"""

"""
Copyright 2009-2016 Olivier Belanger

This file is part of pyo, a python module to help digital signal
processing script creation.

pyo is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

pyo 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 Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with pyo.  If not, see <http://www.gnu.org/licenses/>.

"""
import os
import sys
import time
import builtins
import inspect
import tempfile
import locale
from subprocess import call
from weakref import proxy
from contextlib import redirect_stdout

import builtins

def tobytes(strng, encoding="utf-8"):
    "Convert unicode string to bytes."
    return bytes(strng, encoding=encoding)

if hasattr(builtins, "pyo_use_double"):
    from .._pyo64 import *
    import pyo as current_pyo
else:
    from .._pyo import *
    import pyo as current_pyo

from ._maps import SLMap, SLMapMul
from ._widgets import createCtrlWindow
from ._widgets import createViewTableWindow
from ._widgets import createViewMatrixWindow

######################################################################
### Utilities
######################################################################
current_pyo_path = os.path.dirname(current_pyo.__file__)
SNDS_PATH = os.path.join(current_pyo_path, "lib", "snds")
XNOISE_DICT = {
    "uniform": 0,
    "linear_min": 1,
    "linear_max": 2,
    "triangle": 3,
    "expon_min": 4,
    "expon_max": 5,
    "biexpon": 6,
    "cauchy": 7,
    "weibull": 8,
    "gaussian": 9,
    "poisson": 10,
    "walker": 11,
    "loopseg": 12,
}
FILE_FORMATS = {"wav": 0, "wave": 0, "aif": 1, "aiff": 1, "au": 2, "": 3, "sd2": 4, "flac": 5, "caf": 6, "ogg": 7}
FUNCTIONS_INIT_LINES = {
    "pa_count_host_apis": "pa_count_host_apis()",
    "pa_list_host_apis": "pa_list_host_apis()",
    "pa_get_default_host_api": "pa_get_default_host_api()",
    "pa_get_default_devices_from_host": "pa_get_default_devices_from_host(host)",
    "pa_count_devices": "pa_count_devices()",
    "pa_list_devices": "pa_list_devices()",
    "pa_get_devices_infos": "pa_get_devices_infos()",
    "pa_get_version": "pa_get_version()",
    "pa_get_version_text": "pa_get_version_text()",
    "pa_get_input_devices": "pa_get_input_devices()",
    "pa_get_output_devices": "pa_get_output_devices()",
    "pa_get_default_input": "pa_get_default_input()",
    "pa_get_default_output": "pa_get_default_output()",
    "pa_get_input_max_channels": "pa_get_input_max_channels(x)",
    "pa_get_output_max_channels": "pa_get_output_max_channels(x)",
    "pm_get_default_output": "pm_get_default_output()",
    "pm_get_default_input": "pm_get_default_input()",
    "pm_get_output_devices": "pm_get_output_devices()",
    "pm_get_input_devices": "pm_get_input_devices()",
    "pm_list_devices": "pm_list_devices()",
    "pm_count_devices": "pm_count_devices()",
    "sndinfo": "sndinfo(path, print=False, raise_on_failure=False)",
    "savefile": "savefile(samples, path, sr=44100, channels=1, fileformat=0, sampletype=0, quality=0.4)",
    "savefileFromTable": "savefileFromTable(table, path, fileformat=0, sampletype=0, quality=0.4)",
    "upsamp": "upsamp(path, outfile, up=4, order=128)",
    "downsamp": "downsamp(path, outfile, down=4, order=128)",
    "midiToHz": "midiToHz(x)",
    "hzToMidi": "hzToMidi(x)",
    "midiToTranspo": "midiToTranspo(x)",
    "sampsToSec": "sampsToSec(x)",
    "secToSamps": "secToSamps(x)",
    "beatToDur": "beatToDur(bpm, beat)",
    "linToCosCurve": "linToCosCurve(data, yrange=[0, 1], totaldur=1, points=1024, log=False)",
    "rescale": "rescale(data, xmin=0.0, xmax=1.0, ymin=0.0, ymax=1.0, xlog=False, ylog=False)",
    "distanceToSegment": "distanceToSegment(p, p1, p2, xmin=0.0, xmax=1.0, "
    "ymin=0.0, ymax=1.0, xlog=False, ylog=False)",
    "reducePoints": "reducePoints(pointlist, tolerance=0.02)",
    "serverCreated": "serverCreated()",
    "serverBooted": "serverBooted()",
    "example": "example(cls, dur=5, toprint=True, double=False)",
    "class_args": "class_args(cls)",
    "getVersion": "getVersion()",
    "getPrecision": "getPrecision()",
    "convertStringToSysEncoding": "convertStringToSysEncoding(str)",
    "convertArgsToLists": "convertArgsToLists(*args)",
    "wrap": "wrap(arg, i)",
    "floatmap": "floatmap(x, min=0, max=1, exp=1)",
    "getPyoKeywords": "getPyoKeywords()",
}


def get_random_integer(mx=32767):
    seed = int(str(time.process_time()).split(".")[1])
    return (seed * 31351 + 21997) % mx


def listscramble(lst):
    seed = int(str(time.process_time()).split(".")[1])
    l = lst[:]
    new = []
    pos = 1
    while l:
        pos = (pos * seed) % len(l)
        new.append(l[pos])
        del l[pos]
    return new


def stringencode(st):
    if type(st) is str:
        st = st.encode(locale.getpreferredencoding())
    return st


def sndinfo(path, print=False, raise_on_failure=False):
    """
    Retrieve informations about a soundfile.

    Prints the infos of the given soundfile to the console and returns a
    tuple containing:

    (number of frames, duration in seconds, sampling rate,
     number of channels, file format, sample type)

    :Args:

        path: string
            Path of a valid soundfile.
        print: boolean, optional
            If True, sndinfo will print sound infos to the console.
            Defaults to False.
        raise_on_failure: boolean, optional
            If True, sndinfo will raise an exception when failing to get file info.
            Defaults to False.

    >>> path = SNDS_PATH + '/transparent.aif'
    >>> print(path)
    /home/olivier/.local/lib/python3.9/site-packages/pyo/lib/snds/transparent.aif
    >>> info = sndinfo(path)
    >>> print(info)
    (29877, 0.6774829931972789, 44100.0, 1, 'AIFF', '16 bit int')

    """
    path = stringencode(path)
    info = p_sndinfo(path, print)
    if info is None and raise_on_failure:
        raise PyoError("Could not get file ({:}) info".format(path))
    return info


def savefile(samples, path, sr=44100, channels=1, fileformat=0, sampletype=0, quality=0.4):
    """
    Creates an audio file from a list of floats.

    :Args:

        samples: list of floats
            List of samples data, or list of list of samples data if more than 1 channels.
        path: string
            Full path (including extension) of the new file.
        sr: int, optional
            Sampling rate of the new file. Defaults to 44100.
        channels: int, optional
            Number of channels of the new file. Defaults to 1.
        fileformat: int, optional
            Format type of the new file. Defaults to 0. Supported formats are:

            0. WAVE - Microsoft WAV format (little endian) {.wav, .wave}
            1. AIFF - Apple/SGI AIFF format (big endian) {.aif, .aiff}
            2. AU - Sun/NeXT AU format (big endian) {.au}
            3. RAW - RAW PCM data {no extension}
            4. SD2 - Sound Designer 2 {.sd2}
            5. FLAC - FLAC lossless file format {.flac}
            6. CAF - Core Audio File format {.caf}
            7. OGG - Xiph OGG container {.ogg}
        sampletype ; int, optional
            Bit depth encoding of the audio file. Defaults to 0.
            SD2 and FLAC only support 16 or 24 bit int. Supported types are:

            0. 16 bit int
            1. 24 bit int
            2. 32 bit int
            3. 32 bit float
            4. 64 bit float
            5. U-Law encoded
            6. A-Law encoded
        quality: float, optional
            The encoding quality value, between 0.0 (lowest quality) and
            1.0 (highest quality). This argument has an effect only with
            FLAC and OGG compressed formats. Defaults to 0.4.

    >>> from random import uniform
    >>> import os
    >>> home = os.path.expanduser('~')
    >>> sr, dur, chnls, path = 44100, 5, 2, os.path.join(home, 'noise.aif')
    >>> samples = [[uniform(-0.5,0.5) for i in range(sr*dur)] for i in range(chnls)]
    >>> savefile(samples=samples, path=path, sr=sr, channels=chnls, fileformat=1, sampletype=1)

    """
    path = stringencode(path)
    p_savefile(samples, path, sr, channels, fileformat, sampletype, quality)


def savefileFromTable(table, path, fileformat=0, sampletype=0, quality=0.4):
    """
    Creates an audio file from the content of a table.

    :Args:

        table: PyoTableObject
            Table from which to retrieve the samples to write.
        path: string
            Full path (including extension) of the new file.
        fileformat: int, optional
            Format type of the new file. Defaults to 0. Supported formats are:

            0. WAVE - Microsoft WAV format (little endian) {.wav, .wave}
            1. AIFF - Apple/SGI AIFF format (big endian) {.aif, .aiff}
            2. AU - Sun/NeXT AU format (big endian) {.au}
            3. RAW - RAW PCM data {no extension}
            4. SD2 - Sound Designer 2 {.sd2}
            5. FLAC - FLAC lossless file format {.flac}
            6. CAF - Core Audio File format {.caf}
            7. OGG - Xiph OGG container {.ogg}
        sampletype ; int, optional
            Bit depth encoding of the audio file. Defaults to 0.
            SD2 and FLAC only support 16 or 24 bit int. Supported types are:

            0. 16 bit int
            1. 24 bit int
            2. 32 bit int
            3. 32 bit float
            4. 64 bit float
            5. U-Law encoded
            6. A-Law encoded
        quality: float, optional
            The encoding quality value, between 0.0 (lowest quality) and
            1.0 (highest quality). This argument has an effect only with
            FLAC and OGG compressed formats. Defaults to 0.4.

    >>> import os
    >>> home = os.path.expanduser('~')
    >>> path1 = SNDS_PATH + '/transparent.aif'
    >>> path2 = os.path.join(home, '/transparent2.aif')
    >>> t = SndTable(path1)
    >>> savefileFromTable(table=t, path=path, fileformat=1, sampletype=1)

    """
    path = stringencode(path)
    p_savefileFromTable(table, path, fileformat, sampletype, quality)


def upsamp(path, outfile, up=4, order=128):
    """
    Increases the sampling rate of an audio file.

    :Args:

        path: string
            Full path (including extension) of the audio file to convert.
        outfile: string
            Full path (including extension) of the new file.
        up: int, optional
            Upsampling factor. Defaults to 4.
        order: int, optional
            Length, in samples, of the anti-aliasing lowpass filter.
            Defaults to 128.

    >>> import os
    >>> home = os.path.expanduser('~')
    >>> f = SNDS_PATH+'/transparent.aif'
    >>> # upsample a signal 2 times
    >>> upfile = os.path.join(home, 'trans_upsamp_2.aif')
    >>> upsamp(f, upfile, 2, 256)
    >>> # downsample the upsampled signal 3 times
    >>> downfile = os.path.join(home, 'trans_downsamp_3.aif')
    >>> downsamp(upfile, downfile, 3, 256)

    """
    path = stringencode(path)
    outfile = stringencode(outfile)
    p_upsamp(path, outfile, up, order)


def downsamp(path, outfile, down=4, order=128):
    """
    Decreases the sampling rate of an audio file.

    :Args:

        path: string
            Full path (including extension) of the audio file to convert.
        outfile: string
            Full path (including extension) of the new file.
        down: int, optional
            Downsampling factor. Defaults to 4.
        order: int, optional
            Length, in samples, of the anti-aliasing lowpass filter.
            Defaults to 128.

    >>> import os
    >>> home = os.path.expanduser('~')
    >>> f = SNDS_PATH+'/transparent.aif'
    >>> # upsample a signal 2 times
    >>> upfile = os.path.join(home, 'trans_upsamp_2.aif')
    >>> upsamp(f, upfile, 2, 256)
    >>> # downsample the upsampled signal 3 times
    >>> downfile = os.path.join(home, 'trans_downsamp_3.aif')
    >>> downsamp(upfile, downfile, 3, 256)

    """
    path = stringencode(path)
    outfile = stringencode(outfile)
    p_downsamp(path, outfile, down, order)


class PyoError(Exception):
    """Base class for all pyo exceptions."""


class PyoServerStateException(PyoError):
    """Error raised when an operation requires the server to be booted."""


class PyoArgumentTypeError(PyoError):
    """Error raised when if an object got an invalid argument."""


def isAudioObject(obj):
    "Return True if the argument is an audio object."
    return isinstance(obj, PyoObject) or hasattr(obj, "stream")


def isTableObject(obj):
    "Return True if the argument is a table object."
    return isinstance(obj, PyoTableObject) or hasattr(obj, "tablestream")


def isMatrixObject(obj):
    "Return True if the argument is a matrix object."
    return isinstance(obj, PyoMatrixObject) or hasattr(obj, "matrixstream")


def isPVObject(obj):
    "Return True if the argument is a PV object."
    return isinstance(obj, PyoPVObject) or hasattr(obj, "pv_stream")


def pyoArgsAssert(obj, format, *args):
    """
    Raise an Exception if an object got an invalid argument.

    :Args:

        obj: Pyo object on which method is called.
            Usually "self" in the function call.
        format :
            String of length equal to the number of arguments. Each character
            indicating the expected argument type.

            - O: float or PyoObject
            - o: PyoObject
            - T: float or PyoTableObject
            - t: PyoTableObject
            - m: PyoMatrixObject
            - p: PyoPVObject
            - n: any number (int or float)
            - N: any number (no list-expansion)
            - f: float
            - F: float (no list-expansion)
            - i: integer
            - I: integer (no list-expansion)
            - s: string or unicode
            - S: string or unicode (no list-expansion)
            - b: boolean
            - B: boolean (no list-expansion)
            - l: list
            - L: list or None
            - u: tuple
            - x: sequence (list or tuple)
            - c: callable
            - C: callable (no list-expansion)
            - z: anything
        *args: any
            Arguments passed to the object's method.

    """
    i = 0
    expected = ""
    for i, arg in enumerate(args):
        f = format[i]
        argtype = type(arg)
        if f == "O":
            if not isAudioObject(arg) and argtype not in [list, int, float]:
                expected = "float or PyoObject"
        elif f == "o":
            if not isAudioObject(arg) and argtype not in [list]:
                expected = "PyoObject"
        elif f == "T":
            if not isTableObject(arg) and argtype not in [int, float, list]:
                expected = "int, float or PyoTableObject"
        elif f == "t":
            if not isTableObject(arg) and argtype not in [list]:
                expected = "PyoTableObject"
        elif f == "m":
            if not isMatrixObject(arg) and argtype not in [list]:
                expected = "PyoMatrixObject"
        elif f == "p":
            if not isPVObject(arg) and argtype not in [list]:
                expected = "PyoPVObject"
        elif f == "n":
            if argtype not in [list, int, float]:
                expected = "any number"
        elif f == "N":
            if argtype not in [int, float]:
                expected = "any number - list not allowed"
        elif f == "f":
            if argtype not in [list, float]:
                expected = "float"
        elif f == "F":
            if argtype not in [float]:
                expected = "float - list not allowed"
        elif f == "i":
            if argtype not in [list, int]:
                expected = "integer"
        elif f == "I":
            if argtype not in [int]:
                expected = "integer - list not allowed"
        elif f == "s":
            if argtype not in [list, bytes, str]:
                expected = "string"
        elif f == "S":
            if argtype not in [bytes, str]:
                expected = "string - list not allowed"
        elif f == "b":
            if argtype not in [bool, list, int]:
                expected = "boolean"
        elif f == "B":
            if argtype not in [bool, int]:
                expected = "boolean - list not allowed"
        elif f == "l":
            if argtype not in [list]:
                expected = "list"
        elif f == "L":
            if argtype not in [list, type(None)]:
                expected = "list or None"
        elif f == "u":
            if argtype not in [tuple]:
                expected = "tuple"
        elif f == "x":
            if argtype not in [list, tuple]:
                expected = "list or tuple"
        elif f == "c":
            if not callable(arg) and argtype not in [list, tuple, type(None)]:
                expected = "callable"
        elif f == "C":
            if not callable(arg) and argtype not in [type(None)]:
                expected = "callable - list not allowed"
        elif f == "z":
            pass

        if expected:
            break

    if expected:
        name = obj.__class__.__name__
        err = 'bad argument at position %d to "%s" (%s expected, got %s)'
        raise PyoArgumentTypeError(err % (i, name, expected, argtype))


def convertStringToSysEncoding(strng):
    """
    Convert a string to the current platform file system encoding.

    Returns the new encoded string.

    :Args:

        strng: string
            String to convert.

    """
    if type(strng) not in [bytes, str]:
        strng = strng.decode("utf-8")
    strng = strng.encode(sys.getfilesystemencoding())
    return strng


def convertArgsToLists(*args):
    """
    Convert all arguments to list if not already a list or a PyoObjectBase.
    Return new args and maximum list length.

    """
    converted = list(args)
    for i, arg in enumerate(converted):
        if not isinstance(arg, PyoObjectBase) and not isinstance(arg, list):
            converted[i] = [arg]

    max_length = max(len(arg) for arg in converted)
    converted.append(max_length)
    return tuple(converted)


def wrap(arg, i):
    """
    Return value at position `i` from `arg` with wrap around `arg` length.

    """
    x = arg[i % len(arg)]
    if isinstance(x, PyoObjectBase):
        return x[0]
    else:
        return x


def example(cls, dur=5, toprint=True, double=False):
    """
    Execute the documentation example of the object given as an argument.

    :Args:

        cls: PyoObject class or string
            Class reference of the desired object example. If this argument
            is the string of the full path of an example (as returned by the
            getPyoExamples() function), it will be executed.
        dur: float, optional
            Duration of the example.
        toprint: boolean, optional
            If True, the example script will be printed to the console.
            Defaults to True.
        double: boolean, optional
            If True, force the example to run in double precision (64-bit)
            Defaults to False.

    >>> example(Sine)

    """
    executable = sys.executable
    if not executable or executable is None:
        executable = "python"

    if type(cls) is str and os.path.isfile(cls):
        if toprint:
            print(open(cls, "r").read())
        call([executable, cls])
    else:
        doc = cls.__doc__.splitlines()
        lines = []
        store = False
        for line in doc:
            if not store:
                if ">>> s = Server" in line:
                    store = True
            if store:
                if line.strip() == "":
                    store = False
                else:
                    lines.append(line)

        if lines == []:
            print("There is no manual example for %s object." % cls.__name__)
            return

        ex_lines = [l.lstrip("    ") for l in lines if ">>>" in l or "..." in l]
        if hasattr(builtins, "pyo_use_double") or double:
            ex = "import time\nfrom pyo64 import *\n"
        else:
            ex = "import time\nfrom pyo import *\n"
        for line in ex_lines:
            if ">>>" in line:
                line = line.lstrip(">>> ")
            if "..." in line:
                line = "    " + line.lstrip("... ")
            ex += line + "\n"

        ex += "time.sleep(%f)\ns.stop()\ntime.sleep(0.25)\ns.shutdown()\n" % dur
        f = tempfile.NamedTemporaryFile(delete=False)
        if toprint:
            f.write(tobytes('print("""\n%s\n""")\n' % ex))
        f.write(tobytes(ex))
        f.close()
        call([executable, f.name])


def removeExtraDecimals(x):
    "Return a floating-point value as a string with only two digits."
    if isinstance(x, float):
        return "=%.2f" % x
    elif type(x) in [bytes, str]:
        return '="%s"' % x
    else:
        return "=" + str(x)


def class_args(cls):
    """
    Returns the signature of a pyo class or function.

    This function takes a class or a function reference as input and returns 
    its signature with the default values.

    If the operation can't succeed, the function silently fails and returns
    an empty string.

    :Args:

        cls: callable (class or function from pyo lib)
            Reference of the class or function for which the signature is retrieved.

    >>> print(class_args(Sine))
    >>> 'Sine(freq=1000, phase=0, mul=1, add=0)'

    """
    try:
        arg = str(inspect.signature(cls))
        return cls.__name__ + arg
    except:
        try:
            # Try for a built-in function
            name = cls.__name__
            if name in FUNCTIONS_INIT_LINES:
                return FUNCTIONS_INIT_LINES[name]
        except:
            return ""

def beatToDur(beat, bpm=120):
    """
    Converts a beat value (multiplier of a quarter note) to a duration in seconds.

    :Args:

        beat: float
            Beat value, in multiplier of the quarter note, to convert, according
            to the BPM value, which gives the duration of the quarter note. For
            example, to retrieve the duration of the sixteenth note, for a BPM
            of 90, we would write `beatToDur(1/4, 90)`. `beat` can be a number,
            a list or a tuple.
        bpm: float, optional
            The beat-per-minute value, which gives the duration of the quarter note.
            Defaults to 120. `bpm` can be a number, a list or a tuple.

    >>> bpm = 90
    >>> # Duration of a sixteenth note.
    >>> dur = beatToDur(1/4, 90)
    >>> print(dur)
    1.666666666666
    >>> print(beatToDur(1/4, [60, 90, 120]))
    [0.25, 0.166666666, 0.125]
    >>> print(beatToDur(1/4, (60, 90, 120)))
    (0.25, 0.166666666, 0.125)

    """
    if type(beat) is tuple or type(bpm) is tuple:
        if type(beat) is not tuple:
            beat = (beat,)
        if type(bpm) is not tuple:
            bpm = (bpm,)
        lmax = max(len(beat), len(bpm))
        if lmax == 1:
            return 60.0 / bpm[0] * beat[0]
        else:
            return tuple([60.0 / wrap(bpm, i) * wrap(beat, i) for i in range(lmax)])

    if type(beat) is not list:
        beat = [beat]
    if type(bpm) is not list:
        bpm = [bpm]
    lmax = max(len(beat), len(bpm))
    if lmax == 1:
        return 60.0 / bpm[0] * beat[0]
    else:
        return [60.0 / wrap(bpm, i) * wrap(beat, i) for i in range(lmax)]


def getVersion():
    """
    Returns the version number of the current pyo installation.

    This function returns the version number of the current pyo
    installation as a 3-ints tuple (major, minor, rev).

    The returned tuple for version '0.4.1' will look like: (0, 4, 1)

    >>> print(getVersion())
    >>> (0, 5, 1)

    """
    major, minor, rev = PYO_VERSION.split(".")
    return (int(major), int(minor), int(rev))


def getPrecision():
    """
    Returns the current sample precision as an integer.

    This function returns the current sample precision as an integer,
    either 32 for 32-bit (single) or 64 for 64-bit (double).

    """
    if hasattr(builtins, "pyo_use_double"):
        return 64
    else:
        return 32


def pa_get_default_devices_from_host(host):
    """
    Returns the default input and output devices for a given audio host.

    This function can greatly help finding the device indexes (especially
    on Windows) to give to the server in order to use to desired audio host.

    :Args:

        host: string
            Name of the desired audio host. Possible hosts are:

            - For Windows: mme, directsound, asio, wasapi or wdm-ks.
            - For linux: alsa, oss, pulse or jack.
            - For MacOS: core audio, jack or soundflower.

    Return: (default_input_device, default_output_device)

    """
    host_default_in = pa_get_default_input()
    host_default_out = pa_get_default_output()

    # Retrieve host apis infos.
    tempfile = os.path.join(os.path.expanduser("~"), "pa_retrieve_host_apis")
    with open(tempfile, "w") as f:
        with redirect_stdout(f):
            pa_list_host_apis()

    with open(tempfile, "r") as f:
        lines = f.readlines()

    os.remove(tempfile)

    # Build the list of currently available hosts.
    host_names = []
    for line in lines:
        p1 = line.find("name: ") + 6
        p2 = line.find(",", p1 + 1)
        host_names.append(line[p1:p2])

    # Search for the desired host.
    found = False
    for line in lines:
        if host.lower() in line.lower():
            splitted = line.replace("\n", "").split(", ")
            attributes = [x.split(": ") for x in splitted]
            found = True
            break

    # If not found, return portaudio default values.
    if not found:
        print("Pyo can't find audio host '%s'. Currently available hosts are:" % host)
        for host in host_names:
            print("    %s" % host.lower())
        return host_default_in, host_default_out

    # If found, search default device indexes.
    for attribute in attributes:
        if attribute[0] == "default in":
            host_default_in = int(attribute[1])
        elif attribute[0] == "default out":
            host_default_out = int(attribute[1])

    return host_default_in, host_default_out


def getWeakMethodRef(x):
    "Return a callable object as a weak method reference."
    if type(x) in [list, tuple]:
        tmp = []
        for y in x:
            if hasattr(y, "__self__"):
                y = WeakMethod(y)
            tmp.append(y)
        x = tmp
    else:
        if hasattr(x, "__self__"):
            x = WeakMethod(x)
    return x


class WeakMethod(object):
    """A callable object. Takes one argument to init: 'object.method'.
    Once created, call this object -- MyWeakMethod() --
    and pass args/kwargs as you normally would.
    """

    def __new__(cls, callobj):
        if callable(callobj):
            return super(WeakMethod, cls).__new__(cls)

    def __init__(self, callobj):
        if hasattr(callobj, "__self__"):
            self.target = proxy(callobj.__self__)
            self.method = proxy(callobj.__func__)
            self.isMethod = True
        else:
            self.method = callobj
            self.isMethod = False

    def __call__(self, *args, **kwargs):
        """Call the method with args and kwargs as needed."""
        if self.isMethod:
            return self.method(self.target, *args, **kwargs)
        else:
            return self.method(*args, **kwargs)


######################################################################
### PyoObjectBase -> abstract class for pyo objects
######################################################################
class PyoObjectBase(object):
    """
    Base class for all pyo objects.

    This object encapsulates some common behaviors for all pyo objects.

    One typically inherits from a more specific subclass of this class
    instead of using it directly.

    .. note::

        **Operations allowed on all PyoObjectBase**

        >>> len(obj)      # Return the number of streams managed by the object.
        >>> obj[x]        # Return stream `x` of the object.
        >>>               # `x` is a number from 0 to len(obj)-1.
        >>>               # Illegal indexing returns None.
        >>> dir(obj)      # Return the list of attributes of the object.
        >>> for x in obj: # Can be used as an iterator (iterates over
        ...     pass      # object's audio streams).

    """

    # Descriptive word for this kind of object, for use in printing
    # descriptions of the object. Subclasses need to set this.
    _STREAM_TYPE = ""

    def __init__(self):
        self._base_objs = []
        self._trig_objs = None
        self.__index = 0
        self._stop_delay = -1
        self._is_mul_attribute = False
        self._use_wait_time_on_stop = False
        self._allow_auto_start = True
        self._linked_objects = []
        if not serverCreated():
            raise PyoServerStateException("You must create and boot a Server before creating any audio object.")
        if not serverBooted():
            raise PyoServerStateException("The Server must be booted before creating any audio object.")

    def dump(self):
        """
        Print infos about the current state of the object.

        Print the number of Stream objects managed by the instance
        and the current status of the object's attributes.

        """
        attrs = dir(self)
        pp = "< Instance of %s class >" % self.__class__.__name__
        pp += "\n-----------------------------"
        pp += "\nNumber of %s streams: %d" % (self._STREAM_TYPE, len(self))
        pp += "\n--- Attributes ---"
        for attr in attrs:
            pp += "\n" + attr + ": " + str(getattr(self, attr))
        pp += "\n-----------------------------"
        return pp

    def getBaseObjects(self):
        """
        Return a list of Stream objects managed by the instance.

        """
        return self._base_objs

    def getServer(self):
        """
        Return a reference to the current Server object.

        """
        return self._base_objs[0].getServer()

    def getSamplingRate(self):
        """
        Return the current sampling rate (samples per second), as a float.

        """
        return self._base_objs[0].getServer().getSamplingRate()

    def getBufferSize(self):
        """
        Return the current buffer size (samples per buffer), as an integer.

        """
        return self._base_objs[0].getServer().getBufferSize()

    def allowAutoStart(self, switch=True):
        """
        When autoStartChildren is activated in the Server, call this method
        with False as argument to stop the propagation of play/out/stop methods
        to and from this object. This is useful when an object is used at multiple
        places and you don't want to loose it when you stop one dsp block.

        .. note::

            This flag is ignored if you pass a _base object instead of a PyoObject.
            In the following code, a[0] will still be stopped by a b.stop(wait) call:

                >>> a = Randi(min=0, max=0.3, freq=[1,2])
                >>> a.allowAutoStart(False)
                >>> b = Sine(mul=a[0]).out()

        """
        self._allow_auto_start = switch

    def useWaitTimeOnStop(self):
        """
        When autoStartChildren is activated in the Server, call this method
        to force an object given to the `mul` attribute of another object to
        use the  wait time from the stop method instead of being stopped
        immediately.

        .. note::

            Use wait time on stop is always "on" for _base objects. In the following
            code, a[0] will use the wait time given to b.stop(wait) even if it is
            used as a `mul` attribute:

                >>> a = Randi(min=0, max=0.3, freq=[1,2])
                >>> b = Sine(mul=a[0]).out()

        """
        self._use_wait_time_on_stop = True

    def addLinkedObject(self, x):
        """
        When autoStartChildren is activated in the Server, use this method
        to explicitly add an object in a dsp chain, which is generally
        controlled by the last object of the chain. Here is an example
        where we want an object to be linked to the chain but it can't be
        automatically detected:

        >>> tab = NewTable(length=2, chnls=1)
        >>> rec = TableRec(Sine(500), tab, .01)
        >>> amp = TrigVal(rec["trig"], 0.5)
        >>> osc = Osc(tab, tab.getRate(), mul=Fader(1, 1, mul=.2))
        >>> # "osc" can't know for sure that "rec" should be linked
        >>> # to this dsp chain, so we add it manually.
        >>> osc.addLinkedObject(rec)
        >>> osc.out()

        """
        self._linked_objects.append(x)

    def setStopDelay(self, x):
        """
        Set a specific waiting time when calling the stop method on this object.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            x: float
                New waiting time in seconds.

        .. note::

            if the method setStopDelay(x) was called before calling stop(wait)
            with a positive `wait` value, the `wait` value won't overwrite the
            value given to setStopDelay for the current object, but will be
            the one propagated to children objects. This allow to set a waiting
            time for a specific object with setStopDelay whithout changing the
            global delay time given to the stop method.

            Stop delay value is ignored if you pass a _base object instead of a
            PyoObject. In the following code, a[0] ignores the a.setStopDelay(1)
            call:

                >>> a = Randi(min=0, max=0.3, freq=[1,2])
                >>> a.setStopDelay(1)
                >>> b = Sine(mul=a[0]).out()

        """
        self._stop_delay = x
        return self

    def getStopDelay(self):
        """
        Return the waiting time applied when calling the stop method on this object.

        """
        return self._stop_delay

    def __iter__(self):
        self.__index = 0
        return self

    def __next__(self):
        if self.__index >= len(self):
            raise StopIteration
        x = self[self.__index]
        self.__index += 1
        return x

    def next(self):
        """
        Alias for __next__ method.

        """
        # In Python 2.x, __next__() method is called next().
        return self.__next__()

    def __getitem__(self, i):
        if i == "trig":
            return self._trig_objs
        if type(i) == slice:
            return self._base_objs[i]
        elif isinstance(i, int) and i < len(self._base_objs):
            return self._base_objs[i]
        else:
            if type(i) in [bytes, str]:
                args = (self.__class__.__name__, i)
                print("Object %s has no stream named '%s'!" % args)
            else:
                args = (self._STREAM_TYPE, self.__class__.__name__)
                print("'i' too large in indexing %s object %s!" % args)

    def __setitem__(self, i, x):
        self._base_objs[i] = x

    def __len__(self):
        return len(self._base_objs)

    def __repr__(self):
        return "< Instance of %s class >" % self.__class__.__name__

    def __dir__(self):
        init = getattr(self.__class__, "__init__")
        args, _, _, _, _, _, _ = inspect.getfullargspec(init)
        args = [a for a in args if hasattr(self.__class__, a) and a != "self"]
        return args

    def _autoplay(self, dur=0, delay=0):
        if self.getServer().getAutoStartChildren() and self._allow_auto_start:
            children = [getattr(self, at) for at in dir(self)] + self._linked_objects
            for obj in children:
                if isAudioObject(obj):
                    if not hasattr(obj, "_allow_auto_start"):
                        if obj._getStream().isOutputting():  # if outputting, don't call play().
                            return
                        obj.play(dur[0], delay[0])
                    elif obj._allow_auto_start:
                        if obj.isOutputting():
                            return
                        obj.play(dur, delay)
                elif type(obj) is list:  # Handle list of audio objects.
                    for subobj in obj:
                        if isAudioObject(subobj):
                            if not hasattr(subobj, "_allow_auto_start"):
                                if subobj._getStream().isOutputting():
                                    return
                                subobj.play(dur[0], delay[0])
                            elif subobj._allow_auto_start:
                                if subobj.isOutputting():
                                    return
                                subobj.play(dur, delay)

    def _autostop(self, wait=0):
        if self.getServer().getAutoStartChildren():
            children = [(getattr(self, at), at) for at in dir(self)] + [(obj, "") for obj in self._linked_objects]
            for tup in children:
                if isAudioObject(tup[0]):
                    if not hasattr(tup[0], "_allow_auto_start"):
                        # XXX_base objects always wait, even for mul attribute.
                        tup[0].stop(wait)
                    elif tup[0]._allow_auto_start:
                        if tup[1] == "mul":
                            # Start fadeout immediately.
                            tup[0]._is_mul_attribute = True
                            tup[0].stop(wait)
                            tup[0]._is_mul_attribute = False
                        else:
                            # Every other attributes wait.
                            tup[0].stop(wait)
                # Handle list of audio objects.
                elif type(tup[0]) is list:
                    ismul = tup[1] == "mul"
                    for subobj in tup[0]:
                        if isAudioObject(subobj) and subobj._allow_auto_start:
                            if not hasattr(subobj, "_allow_auto_start"):
                                # XXX_base objects always wait, even for mul attribute.
                                subobj.stop(wait)
                            elif subobj._allow_auto_start:
                                if ismul:
                                    # Start fadeout immediately.
                                    subobj._is_mul_attribute = True
                                    subobj.stop(wait)
                                    subobj._is_mul_attribute = False
                                else:
                                    # Every other attributes wait.
                                    subobj.stop(wait)


######################################################################
### PyoObject -> base class for pyo sound objects
######################################################################
class PyoObject(PyoObjectBase):
    """
    Base class for all pyo objects that manipulate vectors of samples.

    The user should never instantiate an object of this class.

    :Parent: :py:class:`PyoObjectBase`

    :Args:

        mul: float or PyoObject, optional
            Multiplication factor. Defaults to 1.
        add: float or PyoObject, optional
            Addition factor. Defaults to 0.

    .. note::

        **Arithmetics**

        Multiplication, addition, division and substraction can be applied
        between pyo objects or between pyo objects and numbers. Doing so
        returns a Dummy object with the result of the operation.

        >>> # Creates a Dummy object `b` with `mul` set to 0.5.
        >>> # Leaves `a` unchanged.
        >>> b = a * 0.5

        Inplace multiplication, addition, division and substraction can be
        applied between pyo objects or between pyo objects and numbers.
        These operations will replace the `mul` or `add` factor of the object.

        >>> a *= 0.5 # replaces the `mul` attribute of `a`.

        The next operators can only be used with PyoObject, not with
        XXX_base objects.

        **Exponent** and **modulo**

        >>> a ** 10 # returns a Pow object created as: Pow(a, 10)
        >>> 10 ** a # returns a Pow object created as: Pow(10, a)
        >>> a % 4 # returns a Wrap object created as: Wrap(a, 0, 4)
        >>> a % b # returns a Wrap object created as: Wrap(a, 0, b)

        **Unary negative** (**-**)

        >>> -a # returns a Dummy object with negative values of streams in `a`.

        **Comparison operators**

        >>> # Comparison operators return a Compare object.
        >>> x = a < b # same as: x = Compare(a, comp=b, mode="<")
        >>> x = a <= b # same as: Compare(a, comp=b, mode="<=")
        >>> x = a == b # same as: Compare(a, comp=b, mode="==")
        >>> x = a != b # same as: Compare(a, comp=b, mode="!=")
        >>> x = a > b # same as: Compare(a, comp=b, mode=">")
        >>> x = a >= b # same as: Compare(a, comp=b, mode=">=")

        A special case concerns the comparison of a PyoObject with None.
        All operators return False except `a != None`, which returns True.

    """

    _STREAM_TYPE = "audio"

    def __init__(self, mul=1.0, add=0.0):
        PyoObjectBase.__init__(self)
        self._target_dict = {}
        self._signal_dict = {}
        self._callback_dict = {}
        self._keep_trace = []
        self._mul = mul
        self._add = add
        self._op_duplicate = 1
        self._map_list = []
        self._zeros = None
        self._base_players = None
        self._time_objs = None

    def __add__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _add_dummy = ArithmeticDummy([obj + wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            if isinstance(x, PyoObject):
                _add_dummy = x + self
            else:
                _add_dummy = ArithmeticDummy([wrap(self._base_objs, i) + obj for i, obj in enumerate(x)])
        self._keep_trace.append(_add_dummy)
        return _add_dummy

    def __radd__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _add_dummy = ArithmeticDummy([obj + wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            _add_dummy = ArithmeticDummy([wrap(self._base_objs, i) + obj for i, obj in enumerate(x)])
        self._keep_trace.append(_add_dummy)
        return _add_dummy

    def __iadd__(self, x):
        self.setAdd(x)
        return self

    def __sub__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _add_dummy = ArithmeticDummy([obj - wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            if isinstance(x, PyoObject):
                _add_dummy = ArithmeticDummy([wrap(self._base_objs, i) - wrap(x, i) for i in range(lmax)])
            else:
                _add_dummy = ArithmeticDummy([wrap(self._base_objs, i) - obj for i, obj in enumerate(x)])
        self._keep_trace.append(_add_dummy)
        return _add_dummy

    def __rsub__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _add_dummy = ArithmeticDummy([wrap(x, i // self._op_duplicate) - obj for i, obj in enumerate(self._base_objs)])
        else:
            _add_dummy = ArithmeticDummy([obj - wrap(self._base_objs, i) for i, obj in enumerate(x)])
        self._keep_trace.append(_add_dummy)
        return _add_dummy

    def __isub__(self, x):
        self.setSub(x)
        return self

    def __mul__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _mul_dummy = ArithmeticDummy([obj * wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            if isinstance(x, PyoObject):
                _mul_dummy = x * self ### RecursionError: maximum recursion depth exceeded while calling a Python object
            else:
                _mul_dummy = ArithmeticDummy([wrap(self._base_objs, i) * obj for i, obj in enumerate(x)])
        self._keep_trace.append(_mul_dummy)
        return _mul_dummy

    def __rmul__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _mul_dummy = ArithmeticDummy([obj * wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            _mul_dummy = ArithmeticDummy([wrap(self._base_objs, i) * obj for i, obj in enumerate(x)])
        self._keep_trace.append(_mul_dummy)
        return _mul_dummy

    def __imul__(self, x):
        self.setMul(x)
        return self

    def __truediv__(self, x):
        return self.__div__(x)

    def __rtruediv__(self, x):
        return self.__rdiv__(x)

    def __itruediv__(self, x):
        return self.__idiv__(x)

    def __div__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _mul_dummy = ArithmeticDummy([obj / wrap(x, i // self._op_duplicate) for i, obj in enumerate(self._base_objs)])
        else:
            if isinstance(x, PyoObject):
                _mul_dummy = ArithmeticDummy([wrap(self._base_objs, i) / wrap(x, i) for i in range(lmax)])
            else:
                _mul_dummy = ArithmeticDummy([wrap(self._base_objs, i) / obj for i, obj in enumerate(x)])
        self._keep_trace.append(_mul_dummy)
        return _mul_dummy

    def __rdiv__(self, x):
        x, lmax = convertArgsToLists(x)
        if self.__len__() >= lmax:
            _mul_dummy = ArithmeticDummy([wrap(x, i // self._op_duplicate) / obj for i, obj in enumerate(self._base_objs)])
        else:
            _mul_dummy = ArithmeticDummy([obj / wrap(self._base_objs, i) for i, obj in enumerate(x)])
        self._keep_trace.append(_mul_dummy)
        return _mul_dummy

    def __idiv__(self, x):
        self.setDiv(x)
        return self

    def __pow__(self, x):
        return Pow(self, x)

    def __rpow__(self, x):
        return Pow(x, self)

    def __mod__(self, x):
        return Wrap(self, 0, x)

    def __neg__(self):
        if self._zeros is None:
            self._zeros = Sig(0)
        return self._zeros - self

    def __lt__(self, x):
        return self.__do_comp__(comp=x, mode="<")

    def __le__(self, x):
        return self.__do_comp__(comp=x, mode="<=")

    def __eq__(self, x):
        return self.__do_comp__(comp=x, mode="==")

    def __ne__(self, x):
        return self.__do_comp__(comp=x, mode="!=", default=True)

    def __gt__(self, x):
        return self.__do_comp__(comp=x, mode=">")

    def __ge__(self, x):
        return self.__do_comp__(comp=x, mode=">=")

    def __do_comp__(self, comp, mode, default=False):
        if comp is None:
            return default
        else:
            return Compare(self, comp=comp, mode=mode)

    def isPlaying(self, all=False):
        """
        Returns True if the object is currently playing, otherwise, returns False.

        :Args:

            all: boolean, optional
                If True, the object returns a list with the state of all
                streams managed by the object.

                If False, it return a boolean corresponding to the state
                of the first stream.

        """
        pyoArgsAssert(self, "B", all)
        if all:
            return [obj._getStream().isPlaying() for obj in self._base_objs]
        else:
            return self._base_objs[0]._getStream().isPlaying()

    def isOutputting(self, all=False):
        """
        Returns True if the object is outputting.

        Returns True if the object is sending samples to dac,
        otherwise, returns False.

        :Args:

            all: boolean, optional
                If True, the object returns a list with the state of all
                streams managed by the object.

                If False, it return a boolean corresponding to the state
                of the first stream.

        """
        pyoArgsAssert(self, "B", all)
        if all:
            return [obj._getStream().isOutputting() for obj in self._base_objs]
        else:
            return self._base_objs[0]._getStream().isOutputting()

    def get(self, all=False):
        """
        Return the first sample of the current buffer as a float.

        Can be used to convert audio stream to usable Python data.

        Object that implements string identifier for specific audio
        streams must use the corresponding string to specify the stream
        from which to get the value. See get() method definition in these
        object's man pages.

        :Args:

            all: boolean, optional
                If True, the first value of each object's stream
                will be returned as a list.

                If False, only the value of the first object's stream
                will be returned as a float.

        """
        pyoArgsAssert(self, "B", all)
        if not all:
            return self._base_objs[0]._getStream().getValue()
        else:
            return [obj._getStream().getValue() for obj in self._base_objs]

    def _init_play(self):
        temp = self._allow_auto_start
        self._allow_auto_start = False
        self.play()
        self._allow_auto_start = temp

    def play(self, dur=0, delay=0):
        """
        Start processing without sending samples to output.
        This method is called automatically at the object creation.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            dur: float, optional
                Duration, in seconds, of the object's activation. The default
                is 0 and means infinite duration.
            delay: float, optional
                Delay, in seconds, before the object's activation. Defaults to 0.

        """
        pyoArgsAssert(self, "nn", dur, delay)
        dur, delay, lmax = convertArgsToLists(dur, delay)
        if not self.isPlaying() and not self.isOutputting():
            self._autoplay(dur, delay)
        if self._trig_objs is not None:
            if isinstance(self._trig_objs, list):
                for i in range(lmax):
                    for obj in self._trig_objs:
                        obj.play(wrap(dur, i), wrap(delay, i))
            else:
                self._trig_objs.play(dur, delay)
        if self._base_players is not None:
            [obj.play(wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_players)]
        if self._time_objs is not None:
            # We don't send 'dur' argument to time_stream to avoid a stop() call.
            [obj.play(0, wrap(delay, i)) for i, obj in enumerate(self._time_objs)]
        if hasattr(self, "_in_fader"):
            if 0 in dur:
                self._in_fader.play(0, min(delay))
            else:
                durtmp = 0.0
                for i in range(lmax):
                    if (wrap(dur, i) + wrap(delay, i)) > durtmp:
                        durtmp = wrap(dur, i) + wrap(delay, i)
                self._in_fader.play(durtmp, min(delay))
        if hasattr(self, "_in_fader2"):
            if 0 in dur:
                self._in_fader2.play(0, min(delay))
            else:
                durtmp = 0.0
                for i in range(lmax):
                    if (wrap(dur, i) + wrap(delay, i)) > durtmp:
                        durtmp = wrap(dur, i) + wrap(delay, i)
                self._in_fader2.play(durtmp, min(delay))

        [obj.play(wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_objs)]
        return self

    def out(self, chnl=0, inc=1, dur=0, delay=0):
        """
        Start processing and send samples to audio output beginning at `chnl`.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            chnl: int, optional
                Physical output assigned to the first audio stream of the
                object. Defaults to 0.
            inc: int, optional
                Output channel increment value. Defaults to 1.
            dur: float, optional
                Duration, in seconds, of the object's activation. The default
                is 0 and means infinite duration.
            delay: float, optional
                Delay, in seconds, before the object's activation.
                Defaults to 0.

        If `chnl` >= 0, successive streams increment the output number by
        `inc` and wrap around the global number of channels.

        If `chnl` is negative, streams begin at 0, increment
        the output number by `inc` and wrap around the global number of
        channels. Then, the list of streams is scrambled.

        If `chnl` is a list, successive values in the list will be
        assigned to successive streams.

        """
        pyoArgsAssert(self, "iInn", chnl, inc, dur, delay)
        dur, delay, lmax = convertArgsToLists(dur, delay)
        if not self.isPlaying() and not self.isOutputting():
            self._autoplay(dur, delay)
        if self._trig_objs is not None:
            if isinstance(self._trig_objs, list):
                for i in range(lmax):
                    for obj in self._trig_objs:
                        obj.play(wrap(dur, i), wrap(delay, i))
            else:
                self._trig_objs.play(dur, delay)
        if self._base_players is not None:
            [obj.play(wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_players)]
        if self._time_objs is not None:
            # We don't send 'dur' argument to time_stream to avoid a stop() call.
            [obj.play(0, wrap(delay, i)) for i, obj in enumerate(self._time_objs)]
        if hasattr(self, "_in_fader"):
            if 0 in dur:
                self._in_fader.play(0, min(delay))
            else:
                durtmp = 0.0
                for i in range(lmax):
                    if (wrap(dur, i) + wrap(delay, i)) > durtmp:
                        durtmp = wrap(dur, i) + wrap(delay, i)
                self._in_fader.play(durtmp, min(delay))
        if hasattr(self, "_in_fader2"):
            if 0 in dur:
                self._in_fader2.play(0, min(delay))
            else:
                durtmp = 0.0
                for i in range(lmax):
                    if (wrap(dur, i) + wrap(delay, i)) > durtmp:
                        durtmp = wrap(dur, i) + wrap(delay, i)
                self._in_fader2.play(durtmp, min(delay))

        if isinstance(chnl, list):
            [obj.out(wrap(chnl, i), wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_objs)]
        else:
            if chnl < 0:
                [obj.out(i * inc, wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(listscramble(self._base_objs))]
                # prevent normal order to happen.
                while [obj._getStream().getOutputChannel() for obj in self._base_objs] == list(range(len(self._base_objs))):
                    [obj.out(i * inc, wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(listscramble(self._base_objs))]
            else:
                [obj.out(chnl + i * inc, wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_objs)]
        return self

    def stop(self, wait=0):
        """
        Stop processing.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            wait: float, optional
                Delay, in seconds, before the process is actually stopped.
                If autoStartChildren is activated in the Server, this value
                is propagated to the children objects. Defaults to 0.

        .. note::

            if the method setStopDelay(x) was called before calling stop(wait)
            with a positive `wait` value, the `wait` value won't overwrite the
            value given to setStopDelay for the current object, but will be
            the one propagated to children objects. This allow to set a waiting
            time for a specific object with setStopDelay whithout changing the
            global delay time given to the stop method.

            Fader and Adsr objects ignore waiting time given to the stop
            method because they already implement a delayed processing
            triggered by the stop call.

        """
        if self.isPlaying() or self.isOutputting():
            self._autostop(wait)
        if self._is_mul_attribute and not self._use_wait_time_on_stop:
            wait = 0
        if self._stop_delay != -1:
            wait = self._stop_delay

        if self._trig_objs is not None:
            if isinstance(self._trig_objs, list):
                [obj.stop(wait) for obj in self._trig_objs]
            else:
                self._trig_objs.stop(wait)
        if self._base_players is not None:
            [obj.stop(wait) for obj in self._base_players]
        if hasattr(self, "_in_fader"):
            self._in_fader.stop(wait)
        if hasattr(self, "_in_fader2"):
            self._in_fader2.stop(wait)
        # This is not good for TableRec objects, only for Looper.
        # It's moved locally to the Looper definition.
        # if self._time_objs is not None:
        #    [obj.stop() for obj in self._time_objs]
        [obj.stop(wait) for obj in self._base_objs]
        return self

    def mix(self, voices=1):
        """
        Mix the object's audio streams into `voices` streams and return
        a Mix object.

        :Args:

            voices: int, optional
                Number of audio streams of the Mix object created by this
                method. Defaults to 1.

                If more than 1, object's streams are alternated and added into
                Mix object's streams.

        """
        return Mix(self, voices)

    def range(self, min, max):
        """
        Adjust `mul` and `add` attributes according to a given range.

        This function assumes a signal between -1 and 1. Arguments may be
        list of floats for multi-streams objects.

        This method returns `self`, allowing it to be applied at the object
        creation:

        >>> lfo = Sine(freq=1).range(500, 1000)

        :Args:

            min: float
                Minimum value of the output signal.
            max: float
                Maximum value of the output signal.

        """
        pyoArgsAssert(self, "nn", min, max)
        min, max, lmax = convertArgsToLists(min, max)
        if lmax > 1:
            mul = [(wrap(max, i) - wrap(min, i)) * 0.5 for i in range(lmax)]
            add = [(wrap(max, i) + wrap(min, i)) * 0.5 for i in range(lmax)]
        else:
            mul = (max[0] - min[0]) * 0.5
            add = (max[0] + min[0]) * 0.5
        self.setMul(mul)
        self.setAdd(add)
        return self

    def setMul(self, x):
        """
        Replace the `mul` attribute.

        :Args:

            x: float or PyoObject
                New `mul` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._mul = x
        x, _ = convertArgsToLists(x)
        [obj.setMul(wrap(x, i // self._op_duplicate)) for i, obj in enumerate(self._base_objs)]

    def setAdd(self, x):
        """
        Replace the `add` attribute.

        :Args:

            x: float or PyoObject
                New `add` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._add = x
        x, _ = convertArgsToLists(x)
        [obj.setAdd(wrap(x, i // self._op_duplicate)) for i, obj in enumerate(self._base_objs)]

    def setSub(self, x):
        """
        Replace and inverse the `add` attribute.

        :Args:

            x: float or PyoObject
                New inversed `add` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._add = x
        x, _ = convertArgsToLists(x)
        [obj.setSub(wrap(x, i // self._op_duplicate)) for i, obj in enumerate(self._base_objs)]

    def setDiv(self, x):
        """
        Replace and inverse the `mul` attribute.

        :Args:

            x: float or PyoObject
                New inversed `mul` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._mul = x
        x, _ = convertArgsToLists(x)
        [obj.setDiv(wrap(x, i // self._op_duplicate)) for i, obj in enumerate(self._base_objs)]

    def set(self, attr, value, port=0.025, callback=None):
        """
        Replace any attribute with portamento.

        This method is intended to be applied on attributes that are not
        already assigned to PyoObjects. It will work only with floats or
        list of floats.

        :Args:

            attr: string
                Name of the attribute as a string.
            value: float
                New value.
            port: float, optional
                Time, in seconds, to reach the new value.
            callback: callable, optional
                A python function to be called at the end of the ramp. If the
                end of the ramp is not reached (ex.: called again before the
                end of the portamento), the callback will not be called.

        """
        pyoArgsAssert(self, "SnnC", attr, value, port, callback)
        self._target_dict[attr] = value
        self._callback_dict[attr] = callback
        init = getattr(self, attr)
        if attr in self._signal_dict:
            if isinstance(self._signal_dict[attr], VarPort):
                if self._signal_dict[attr].isPlaying():
                    init = self._signal_dict[attr].get(True)
                    self._signal_dict[attr].stop()
        self._signal_dict[attr] = VarPort(value, port, init, self._reset_from_set, attr)
        setattr(self, attr, self._signal_dict[attr])

    def _reset_from_set(self, attr=None):
        if isinstance(getattr(self, attr), VarPort):
            setattr(self, attr, self._target_dict[attr])
            if self._callback_dict[attr] is not None:
                self._callback_dict[attr]()
                del self._callback_dict[attr]
        self._signal_dict[attr].stop()

    def ctrl(self, map_list=None, title=None, wxnoserver=False):
        """
        Opens a sliders window to control the parameters of the object.
        SLMap has a `dataOnly` attribute to identify parameters that don't
        audio signal as control but only discrete values.

        If a list of values are given to a parameter, a multisliders
        will be used to control each stream independently.

        :Args:

            map_list: list of SLMap objects, optional
                Users defined set of parameters scaling. There is default
                scaling for each object that accept `ctrl` method.
            title: string, optional
                Title of the window. If none is provided, the name of the
                class is used.
            wxnoserver: boolean, optional
                With wxPython graphical toolkit, if True, tells the
                interpreter that there will be no server window.

        If `wxnoserver` is set to True, the interpreter will not wait for
        the server GUI before showing the controller window.

        """
        if map_list is None:
            map_list = self._map_list
        if map_list == []:
            clsname = self.__class__.__name__
            print("There are no controls for %s object." % clsname)
            return
        createCtrlWindow(self, map_list, title, wxnoserver)

    @property
    def mul(self):
        """float or PyoObject. Multiplication factor."""
        return self._mul

    @mul.setter
    def mul(self, x):
        self.setMul(x)

    @property
    def add(self):
        """float or PyoObject. Addition factor."""
        return self._add

    @add.setter
    def add(self, x):
        self.setAdd(x)


######################################################################
### PyoTableObject -> base class for pyo table objects
######################################################################
class PyoTableObject(PyoObjectBase):
    """
    Base class for all pyo table objects.

    A table object is a buffer memory to store precomputed samples.

    The user should never instantiate an object of this class.

    :Parent: :py:class:`PyoObjectBase`

    :Args:

        size: int
            Length of the table in samples. Usually provided by the
            child object.

    """

    _STREAM_TYPE = "table"

    def __init__(self, size=0):
        PyoObjectBase.__init__(self)
        self._size = size
        self.viewFrame = None
        self.graphFrame = None

    def save(self, path, format=0, sampletype=0, quality=0.4):
        """
        Writes the content of the table in an audio file.

        The sampling rate of the file is the sampling rate of the server
        and the number of channels is the number of table streams of the
        object.

        :Args:

            path: string
                Full path (including extension) of the new file.
            format: int, optional
                Format type of the new file. Supported formats are:
                    0. WAVE - Microsoft WAV format (little endian) {.wav, .wave}
                    1. AIFF - Apple/SGI AIFF format (big endian) {.aif, .aiff}
                    2. AU - Sun/NeXT AU format (big endian) {.au}
                    3. RAW - RAW PCM data {no extension}
                    4. SD2 - Sound Designer 2 {.sd2}
                    5. FLAC - FLAC lossless file format {.flac}
                    6. CAF - Core Audio File format {.caf}
                    7. OGG - Xiph OGG container {.ogg}
            sampletype: int, optional
                Bit depth encoding of the audio file.

                SD2 and FLAC only support 16 or 24 bit int. Supported types are:
                    0. 16 bit int (default)
                    1. 24 bit int
                    2. 32 bit int
                    3. 32 bit float
                    4. 64 bit float
                    5. U-Law encoded
                    6. A-Law encoded
            quality: float, optional
                The encoding quality value, between 0.0 (lowest quality) and
                1.0 (highest quality). This argument has an effect only with
                FLAC and OGG compressed formats. Defaults to 0.4.

        """
        pyoArgsAssert(self, "SIIN", path, format, sampletype, quality)
        ext = path.rsplit(".")
        if len(ext) >= 2:
            ext = ext[-1].lower()
            if ext in FILE_FORMATS:
                format = FILE_FORMATS[ext]
        savefileFromTable(self, path, format, sampletype, quality)

    def write(self, path, oneline=True):
        """
        Writes the content of the table in a text file.

        This function can be used to store the table data as a
        list of floats into a text file.

        :Args:

            path: string
                Full path of the generated file.
            oneline: boolean, optional
                If True, list of samples will inserted on one line.

                If False, list of samples will be truncated to 8 floats
                per line.

        """
        pyoArgsAssert(self, "SB", path, oneline)
        f = open(path, "w")
        if oneline:
            f.write(str([obj.getTable() for obj in self._base_objs]))
        else:
            text = "["
            for obj in self._base_objs:
                text += "["
                for i, val in enumerate(obj.getTable()):
                    if (i % 8) == 0:
                        text += "\n"
                    text += str(val) + ", "
                text += "]"
            text += "]"
            f.write(text)
        f.close()

    def read(self, path):
        """
        Reads the content of a text file and replaces the table data
        with the values stored in the file.

        :Args:

            path: string
                Full path of the file to read.

        The format is a list of lists of floats. For example, A two
        tablestreams object must be given a content like this:

        [ [ 0.0, 1.0, 0.5, ... ], [ 1.0, 0.99, 0.98, 0.97, ... ] ]

        Each object's tablestream will be resized according to the
        length of the lists.

        """
        pyoArgsAssert(self, "S", path)
        f = open(path, "r")
        f_list = eval(f.read())
        f_len = len(f_list)
        f.close()
        [obj.setData(f_list[i % f_len]) for i, obj in enumerate(self._base_objs)]
        # adjust the _size attribute.
        if f_len == 1:
            self._size = self._base_objs[0].getSize()
        else:
            self._size = [obj.getSize() for obj in self._base_objs]
        self.refreshView()

    def getBuffer(self, chnl=0):
        """
        Return a reference to the underlying object implementing the buffer protocol.

        With the buffer protocol, a table can be referenced and modified,
        without copying the data, with numpy functions. To create an array
        using the same memory as the table:

            >>> t = SndTable(SNDS_PATH+"/transparent.aif")
            >>> arr = numpy.asarray(t.getBuffer())

        Now, every changes applied to the array will be reflected in
        the SndTable. This method works for a single channel only.

        :Args:

            chnl: int, optional
                The channel in the table for which to obtain the underlying buffer.
                Defaults to 0.

        For more details about the buffer protocol, see PEP 3118 and the
        python documentation.

        """
        if chnl < 0 or chnl >= len(self):
            print("getBuffer(chnl): `chnl` argument out-of-range...")
        else:
            return self._base_objs[chnl].getTableStream()

    def setSize(self, size):
        """
        Change the size of the table.

        This will usually regenerate the table content.

        :Args:

            size: int
                New table size in samples.

        """
        pyoArgsAssert(self, "I", size)
        self._size = size
        [obj.setSize(size) for obj in self._base_objs]
        self.refreshView()

    def getSize(self, all=False):
        """
        Return table size in samples.

        :Args:

            all: boolean
                If the table contains more than one stream and `all` is True,
                returns a list of all sizes. Otherwise, returns only the
                first size as an int. Defaults to False.

        """
        pyoArgsAssert(self, "B", all)
        if all:
            return [obj.getSize() for obj in self._base_objs]
        else:
            if isinstance(self._size, list):
                return self._size[0]
            else:
                return self._size

    def getRate(self, all=False):
        """
        Return the frequency in cps at which the table will be read at its
        original pitch.

        :Args:

            all: boolean
                If the table contains more than one stream and `all` is True,
                returns a list of all frequencies. Otherwise, returns only the
                first frequency as a float. Defaults to False.

        """
        pyoArgsAssert(self, "B", all)
        _rate = [obj.getRate() for obj in self._base_objs]

        if all and len(_rate) > 1:
            return _rate
        else:
            return _rate[0]

    def getDur(self, all=False):
        """
        Return the duration of the table in seconds.

        :Args:

            all: boolean
                If the table contains more than one stream and `all` is True,
                returns a list of all durations. Otherwise, returns only the
                first duration as a float. Defaults to False.

        """
        _rate = self.getRate(all)
        if type(_rate) is list:
            return [1.0 / x for x in _rate]
        else:
            return 1.0 / _rate

    def put(self, value, pos=0):
        """
        Puts a value at specified sample position in the table.

        If the object has more than 1 tablestream, the default is to
        record the value in each table. User can call obj[x].put()
        to record into a specific table.

        :Args:

            value: float
                Value, as floating-point, to record in the table.
            pos: int, optional
                Position, in samples, where to record value.
                Can write backward with negative position. Defaults to 0.

        """
        pyoArgsAssert(self, "NI", value, pos)
        [obj.put(value, pos) for obj in self._base_objs]
        self.refreshView()

    def get(self, pos):
        """
        Returns the value, as float, stored at a specific position in the table.

        If the object has more than 1 tablestream, the default is to
        return a list with the value of each tablestream. User can call
        obj[x].get() to get the value of a specific table.

        :Args:

            pos: int, optional
                Position, in samples, where to read the value.
                Can read backward with negative position. Defaults to 0.

        """
        pyoArgsAssert(self, "I", pos)
        values = [obj.get(pos) for obj in self._base_objs]
        if len(values) == 1:
            return values[0]
        else:
            return values

    def getTable(self, all=False):
        """
        Returns the content of the table as list of floats.

        :Args:

            all: boolean, optional
                If True, all sub tables are retrieved and returned as a list
                of list of floats.

                If False, a single list containing the content of the first
                subtable (or the only one) is returned.

        """
        pyoArgsAssert(self, "B", all)
        if all:
            return [obj.getTable() for obj in self._base_objs]
        else:
            return self._base_objs[0].getTable()

    def normalize(self, level=0.99):
        """
        Normalizes table samples to a given level.

        :Args:

            level: float, optional
                Samples will be normalized between -level and +level.
                Defaults to 0.99.

        """
        [obj.normalize(level) for obj in self._base_objs]
        self.refreshView()
        return self

    def reset(self):
        """
        Resets table samples to 0.0.

        """
        [obj.reset() for obj in self._base_objs]
        self.refreshView()
        return self

    def removeDC(self):
        """
        Filter out DC offset from the table's data.

        """
        [obj.removeDC() for obj in self._base_objs]
        self.refreshView()
        return self

    def reverse(self):
        """
        Reverse the table's data in time.

        """
        [obj.reverse() for obj in self._base_objs]
        self.refreshView()
        return self

    def invert(self):
        """
        Reverse the table's data in amplitude.

        """
        [obj.invert() for obj in self._base_objs]
        self.refreshView()
        return self

    def rectify(self):
        """
        Positive rectification of the table's data.

        """
        [obj.rectify() for obj in self._base_objs]
        self.refreshView()
        return self

    def pow(self, exp=10):
        """
        Apply a power function on each sample in the table.

        :Args:

            exp: float, optional
                Exponent factor. Defaults to 10.

        """
        pyoArgsAssert(self, "N", exp)
        [obj.pow(exp) for obj in self._base_objs]
        self.refreshView()
        return self

    def bipolarGain(self, gpos=1, gneg=1):
        """
        Apply different gain factor for positive and negative samples.

        :Args:

            gpos: float, optional
                Gain factor for positive samples. Defaults to 1.
            gneg: float, optional
                Gain factor for negative samples. Defaults to 1.

        """
        pyoArgsAssert(self, "NN", gpos, gneg)
        [obj.bipolarGain(gpos, gneg) for obj in self._base_objs]
        self.refreshView()
        return self

    def lowpass(self, freq=1000):
        """
        Apply a one-pole lowpass filter on table's samples.

        :Args:

            freq: float, optional
                Filter's cutoff, in Hertz. Defaults to 1000.

        """
        pyoArgsAssert(self, "N", freq)
        [obj.lowpass(freq) for obj in self._base_objs]
        self.refreshView()
        return self

    def fadein(self, dur=0.1, shape=0):
        """
        Apply a gradual increase in the level of the table's samples.

        :Args:

            dur: float, optional
                Fade in duration, in seconds. Defaults to 0.1.
            shape: int, optional
                Curve type used to shape the fadein. Available curves:
                    0: linear (default)
                    1: sqrt
                    2: sin
                    3: squared

        """
        pyoArgsAssert(self, "NI", dur, shape)
        if shape < 0 or shape > 3:
            shape = 0
        [obj.fadein(dur, shape) for obj in self._base_objs]
        self.refreshView()
        return self

    def fadeout(self, dur=0.1, shape=0):
        """
        Apply a gradual decrease in the level of the table's samples.

        :Args:

            dur: float, optional
                Fade out duration, in seconds. Defaults to 0.1.
            shape: int, optional
                Curve type used to shape the fadein. Available curves:
                    0: linear (default)
                    1: sqrt
                    2: sin
                    3: squared

        """
        pyoArgsAssert(self, "NI", dur, shape)
        if shape < 0 or shape > 3:
            shape = 0
        [obj.fadeout(dur, shape) for obj in self._base_objs]
        self.refreshView()
        return self

    def add(self, x):
        """
        Performs addition on the table values.

        Adds the argument to each table values, position by position
        if the argument is a list or another PyoTableObject.

        :Args:

            x: float, list or PyoTableObject
                value(s) to add.

        """
        pyoArgsAssert(self, "T", x)
        if isinstance(x, list):
            if isinstance(x[0], list):
                [obj.add(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
            else:
                [obj.add(x) for obj in self._base_objs]
        else:
            x, _ = convertArgsToLists(x)
            [obj.add(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
        self.refreshView()
        return self

    def sub(self, x):
        """
        Performs substraction on the table values.

        Substracts the argument to each table values, position by position
        if the argument is a list or another PyoTableObject.

        :Args:

            x: float, list or PyoTableObject
                value(s) to substract.

        """
        pyoArgsAssert(self, "T", x)
        if isinstance(x, list):
            if isinstance(x[0], list):
                [obj.sub(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
            else:
                [obj.sub(x) for obj in self._base_objs]
        else:
            x, _ = convertArgsToLists(x)
            [obj.sub(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
        self.refreshView()
        return self

    def mul(self, x):
        """
        Performs multiplication on the table values.

        Multiply each table values by the argument, position by position
        if the argument is a list or another PyoTableObject.

        :Args:

            x: float, list or PyoTableObject
                value(s) to multiply.

        """
        pyoArgsAssert(self, "T", x)
        if isinstance(x, list):
            if isinstance(x[0], list):
                [obj.mul(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
            else:
                [obj.mul(x) for obj in self._base_objs]
        else:
            x, _ = convertArgsToLists(x)
            [obj.mul(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
        self.refreshView()
        return self

    def div(self, x):
        """
        Performs division on the table values.

        Divide each table values by the argument, position by position
        if the argument is a list or another PyoTableObject.

        :Args:

            x: float, list or PyoTableObject
                value(s) used to divide.

        """
        pyoArgsAssert(self, "T", x)
        if isinstance(x, list):
            if isinstance(x[0], list):
                [obj.div(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
            else:
                [obj.div(x) for obj in self._base_objs]
        else:
            x, _ = convertArgsToLists(x)
            [obj.div(wrap(x, i)) for i, obj in enumerate(self._base_objs)]
        self.refreshView()
        return self

    def copyData(self, table, srcpos=0, destpos=0, length=-1):
        """
        Copy samples from a source table.

        Copy `length` samples from a source table to this table.

        :Args:

            table: PyoTableObject
                The source table.
            srcpos: int, optional
                The start position, in samples, in the source table.
                Can read backward with negative position. Defaults to 0.
            destpos ; int, optional
                The start position, in samples, in the destination (self) table.
                Can read backward with negative position. Defaults to 0.
            length: int, optional
                The number of samples to copy from source to destination. if
                length is negative, the length of the smallest table is used.
                Defaults to -1.

        """
        pyoArgsAssert(self, "tIII", table, srcpos, destpos, length)
        [obj.copyData(table[i], srcpos, destpos, length) for i, obj in enumerate(self._base_objs)]
        self.refreshView()

    def rotate(self, pos):
        """
        Rotate the table content to the left around the position given as argument.

        Samples between the given position and the end of the table will
        be relocated in front of the samples from the beginning to the
        given position.

        :Args:

            pos: int
                The rotation position in samples. A negative position means
                a rotation to the right.

        """
        pyoArgsAssert(self, "I", pos)
        [obj.rotate(pos) for obj in self._base_objs]
        self.refreshView()

    def copy(self):
        """
        Returns a deep copy of the object.

        """
        args = [getattr(self, att) for att in self.__dir__()]
        if self.__class__.__name__ == "SndTable":
            _size = self.getSize()
            if not isinstance(_size, list):
                _size = [_size]
            _chnls = len(self._base_objs)
            args[0] = None
            args.append(_chnls)
            newtable = getattr(current_pyo, self.__class__.__name__)(*args)
            baseobjs = newtable.getBaseObjects()
            [obj.setSize(_size[i % len(_size)]) for i, obj in enumerate(baseobjs)]
            [obj.copy(self[i]) for i, obj in enumerate(newtable.getBaseObjects())]
        else:
            newtable = getattr(current_pyo, self.__class__.__name__)(*args)
            [obj.copy(self[i]) for i, obj in enumerate(newtable.getBaseObjects())]
        return newtable

    def view(self, title="Table waveform", wxnoserver=False):
        """
        Opens a window showing the contents of the table.

        :Args:

            title: string, optional
                Window title. Defaults to "Table waveform".
            wxnoserver: boolean, optional
                With wxPython graphical toolkit, if True, tells the
                interpreter that there will be no server window.

        If `wxnoserver` is set to True, the interpreter will not wait for
        the server GUI before showing the controller window.

        """
        pyoArgsAssert(self, "SB", title, wxnoserver)
        samples = self._base_objs[0].getViewTable((500, 200))
        createViewTableWindow(samples, title, wxnoserver, self.__class__.__name__, self)

    def _setViewFrame(self, frame):
        self.viewFrame = frame

    def _setGraphFrame(self, frame):
        self.graphFrame = frame

    def _get_current_data(self):
        # Children must override this method.
        return []

    def refreshView(self):
        """
        Updates the graphical display of the table, if applicable.

        """
        if self.viewFrame is not None:
            size = self.viewFrame.wavePanel.GetSize()
            samples = self._base_objs[0].getViewTable((size[0], size[1]))
            self.viewFrame.update(samples)
        if self.graphFrame is not None:
            data = self._get_current_data()
            length = len(data)
            flength = self.graphFrame.getLength()
            if length < flength:
                data = data + [0] * (flength - length)
            elif length > flength:
                data = data[:flength]
            self.graphFrame.update(data)

    @property
    def size(self):
        """int. Table size in samples."""
        return self._size

    @size.setter
    def size(self, x):
        self.setSize(x)


######################################################################
### PyoMatrixObject -> base class for pyo matrix objects
######################################################################
class PyoMatrixObject(PyoObjectBase):
    """
    Base class for all pyo matrix objects.

    A matrix object is a 2 dimensions buffer memory to store
    precomputed samples.

    The user should never instantiate an object of this class.

    :Parent: :py:class:`PyoObjectBase`

    """

    _STREAM_TYPE = "matrix"

    def __init__(self):
        self._size = (0, 0)
        PyoObjectBase.__init__(self)
        self.viewFrame = None

    def write(self, path):
        """
        Writes the content of the matrix into a text file.

        This function can be used to store the matrix data as a
        list of list of floats into a text file.

        :Args:

            path: string
                Full path of the generated file.

        """
        pyoArgsAssert(self, "S", path)
        f = open(path, "w")
        f.write(str([obj.getData() for obj in self._base_objs]))
        f.close()

    def read(self, path):
        """
        Reads the content of a text file and replaces the matrix data
        with the values in the file.

        Format is a list of lists of list of floats. For example, A two
        matrixstreams object must be given a content like this:

        [ [ [0.0 ,1.0, 0.5, ... ], [1.0, 0.99, 0.98, 0.97, ... ] ],
        [ [0.0, 1.0, 0.5, ... ], [1.0, 0.99, 0.98, 0.97, ... ] ] ]

        Each object's matrixstream will be resized according to the
        length of the lists, but the number of matrixstreams must be
        the same.

        :Args:

            path: string
                Full path of the file to read.

        """
        pyoArgsAssert(self, "S", path)
        f = open(path, "r")
        f_list = eval(f.read())
        f_len = len(f_list)
        f.close()
        [obj.setData(f_list[i % f_len]) for i, obj in enumerate(self._base_objs)]

    def getSize(self):
        """
        Returns matrix size in samples. Size is a tuple (x, y).

        """
        return self._size

    def normalize(self, level=0.99):
        """
        Normalize matrix samples to a given level.

        :Args:
            level: float, optional
                Samples will be normalized between -level and +level.
                Defaults to 0.99.

        """
        [obj.normalize(level) for obj in self._base_objs]
        return self

    def blur(self):
        """
        Apply a simple gaussian blur on the matrix.

        """
        [obj.blur() for obj in self._base_objs]

    def boost(self, min=-1.0, max=1.0, boost=0.01):
        """
        Boost the constrast of values in the matrix.

        :Args:

            min: float, optional
                Minimum value. Defaults to -1.0.
            max: float, optional
                Maximum value. Defaults to 1.0.
            boost: float, optional
                Amount of boost applied on each value. Defaults to 0.01.

        """
        pyoArgsAssert(self, "NNN", min, max, boost)
        [obj.boost(min, max, boost) for obj in self._base_objs]

    def put(self, value, x=0, y=0):
        """
        Puts a value at specified position in the matrix.

        If the object has more than 1 matrixstream, the default is to
        record the value in each matrix. User can call obj[x].put()
        to record in a specific matrix.

        :Args:

            value: float
                Value, as floating-point, to record in the matrix.
            x: int, optional
                X position where to record value. Defaults to 0.
            y: int, optional
                Y position where to record value. Defaults to 0.

        """
        pyoArgsAssert(self, "NII", value, x, y)
        [obj.put(value, x, y) for obj in self._base_objs]

    def get(self, x=0, y=0):
        """
        Returns the value, as float, at specified position in the matrix.

        If the object has more than 1 matrixstream, the default is to
        return a list with the value of each matrixstream. User can call
        obj[x].get() to get the value of a specific matrix.

        :Args:

            x: int, optional
                X position where to get value. Defaults to 0.
            y: int, optional
                Y position where to get value. Defaults to 0.

        """
        pyoArgsAssert(self, "II", x, y)
        values = [obj.get(x, y) for obj in self._base_objs]
        if len(values) == 1:
            return values[0]
        else:
            return values

    def getInterpolated(self, x=0.0, y=0.0):
        """
        Returns the value, as float, at a normalized position in the matrix.

        If the object has more than 1 matrixstream, the default is to
        return a list with the value of each matrixstream. User can call
        obj[x].getInterpolated() to get the value of a specific matrix.

        :Args:

            x: float {0 -> 1}
                X normalized position where to get value. Defaults to 0.0.
            y: int {0 -> 1}
                Y normalized position where to get value. Defaults to 0.0.

        """
        pyoArgsAssert(self, "FF", x, y)
        values = [obj.getInterpolated(x, y) for obj in self._base_objs]
        if len(values) == 1:
            return values[0]
        else:
            return values

    def view(self, title="Matrix viewer", wxnoserver=False):
        """
        Opens a window showing the contents of the matrix.

        :Args:

            title: string, optional
                Window title. Defaults to "Matrix viewer".
            wxnoserver: boolean, optional
                With wxPython graphical toolkit, if True, tells the
                interpreter that there will be no server window.

        If `wxnoserver` is set to True, the interpreter will not wait for
        the server GUI before showing the controller window.

        """
        pyoArgsAssert(self, "SB", title, wxnoserver)
        samples = self._base_objs[0].getImageData()
        createViewMatrixWindow(samples, self.getSize(), title, wxnoserver, self)

    def _setViewFrame(self, frame):
        self.viewFrame = frame

    def refreshView(self):
        """
        Updates the graphical display of the matrix, if applicable.

        """
        if self.viewFrame is not None:
            samples = self._base_objs[0].getImageData()
            self.viewFrame.update(samples)


######################################################################
### PyoObject -> base class for pyo phase vocoder objects
######################################################################
class PyoPVObject(PyoObjectBase):
    """
    Base class for objects working with phase vocoder's magnitude and frequency streams.

    The user should never instantiate an object of this class.

    :Parent: :py:class:`PyoObjectBase`

    """

    _STREAM_TYPE = "pvoc"

    def __init__(self):
        PyoObjectBase.__init__(self)
        self._target_dict = {}
        self._signal_dict = {}
        self._map_list = []
        self._base_players = None

    def isPlaying(self, all=False):
        """
        Returns True if the object is playing, otherwise, returns False.

        :Args:

            all: boolean, optional
                If True, the object returns a list with the state of all
                streams managed by the object.

                If False, it return a boolean corresponding to the state
                of the first stream.

        """
        pyoArgsAssert(self, "B", all)
        if all:
            return [obj._getStream().isPlaying() for obj in self._base_objs]
        else:
            return self._base_objs[0]._getStream().isPlaying()

    def _init_play(self):
        temp = self._allow_auto_start
        self._allow_auto_start = False
        self.play()
        self._allow_auto_start = temp

    def play(self, dur=0, delay=0):
        """
        Start processing without sending samples to output.
        This method is called automatically at the object creation.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            dur: float, optional
                Duration, in seconds, of the object's activation.
                The default is 0 and means infinite duration.
            delay: float, optional
                Delay, in seconds, before the object's activation.
                Defaults to 0.

        """
        pyoArgsAssert(self, "nn", dur, delay)
        dur, delay, _ = convertArgsToLists(dur, delay)
        if not self.isPlaying():
            self._autoplay(dur, delay)
        if self._trig_objs is not None:
            self._trig_objs.play(dur, delay)
        if self._base_players is not None:
            [obj.play(wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_players)]
        [obj.play(wrap(dur, i), wrap(delay, i)) for i, obj in enumerate(self._base_objs)]
        return self

    def stop(self, wait=0):
        """
        Stop processing.

        This method returns `self`, allowing it to be applied at the object
        creation.

        :Args:

            wait: float, optional
                Delay, in seconds, before the process is actually stopped.
                If autoStartChildren is activated in the Server, this value
                is propagated to the children objects. Defaults to 0.

        .. note::

            if the method setStopDelay(x) was called before calling stop(wait)
            with a positive `wait` value, the `wait` value won't overwrite the
            value given to setStopDelay for the current object, but will be
            the one propagated to children objects. This allow to set a waiting
            time for a specific object with setStopDelay whithout changing the
            global delay time given to the stop method.

        """
        if self.isPlaying():
            self._autostop(wait)
        if self._stop_delay != -1:
            wait = self._stop_delay

        if self._trig_objs is not None:
            self._trig_objs.stop(wait)
        if self._base_players is not None:
            [obj.stop(wait) for obj in self._base_players]
        [obj.stop(wait) for obj in self._base_objs]
        return self

    def set(self, attr, value, port=0.025):
        """
        Replace any attribute with portamento.

        This method is intended to be applied on attributes that are not
        already assigned to PyoObjects. It will work only with floats or
        list of floats.

        :Args:

            attr: string
                Name of the attribute as a string.
            value: float
                New value.
            port: float, optional
                Time, in seconds, to reach the new value.

        """
        pyoArgsAssert(self, "Snn", attr, value, port)
        self._target_dict[attr] = value
        init = getattr(self, attr)
        if attr in self._signal_dict:
            if isinstance(self._signal_dict[attr], VarPort):
                if self._signal_dict[attr].isPlaying():
                    init = self._signal_dict[attr].get(True)
                    self._signal_dict[attr].stop()
        self._signal_dict[attr] = VarPort(value, port, init, self._reset_from_set, attr)
        setattr(self, attr, self._signal_dict[attr])

    def _reset_from_set(self, attr=None):
        if isinstance(getattr(self, attr), VarPort):
            setattr(self, attr, self._target_dict[attr])
        self._signal_dict[attr].stop()

    def ctrl(self, map_list=None, title=None, wxnoserver=False):
        """
        Opens a sliders window to control the parameters of the object.
        Only parameters that can be set to a PyoObject are allowed
        to be mapped on a slider.

        If a list of values are given to a parameter, a multisliders
        will be used to control each stream independently.

        :Args:

            map_list: list of SLMap objects, optional
                Users defined set of parameters scaling. There is default
                scaling for each object that accept `ctrl` method.
            title: string, optional
                Title of the window. If none is provided, the name of the
                class is used.
            wxnoserver: boolean, optional
                With wxPython graphical toolkit, if True, tells the
                interpreter that there will be no server window.

        If `wxnoserver` is set to True, the interpreter will not wait for
        the server GUI before showing the controller window.

        """
        if map_list is None:
            map_list = self._map_list
        if map_list == []:
            clsname = self.__class__.__name__
            print("There are no controls for %s object." % clsname)
            return
        createCtrlWindow(self, map_list, title, wxnoserver)


######################################################################
### Internal classes -> Used by pyo
######################################################################
class Mix(PyoObject):
    """
    Mix audio streams to arbitrary number of streams.

    Mix the object's audio streams as `input` argument into `voices`
    streams.

    :Parent: :py:class:`PyoObject`

    :Args:

        input: PyoObject or list of PyoObjects
            Input signal(s) to mix the streams.
        voices: int, optional
            Number of streams of the Mix object. If more than 1, input
            object's streams are alternated and added into Mix object's
            streams. Defaults to 1.

    .. note::

        The mix method of PyoObject creates and returns a new Mix object
        with mixed streams of the object that called the method. User
        don't have to instantiate this class directly. These two calls
        are identical:

        >>> b = a.mix()
        >>> b = Mix(a)

        The `mul` and `add` arguments are relative to the number of voices,
        ie. if `len(mul)` is bigger than `voices`, last mul values will simply 
        be ignored, even if the number of input streams to mix is higher.

    >>> s = Server().boot()
    >>> s.start()
    >>> a = Sine([random.uniform(400,600) for i in range(50)], mul=.02)
    >>> b = Mix(a, voices=2).out()
    >>> print(len(a))
    50
    >>> print(len(b))
    2

    """

    def __init__(self, input, voices=1, mul=1, add=0):
        pyoArgsAssert(self, "oIOO", input, voices, mul, add)
        PyoObject.__init__(self, mul, add)
        self._input = input
        mul, add, lmax = convertArgsToLists(mul, add)
        if isinstance(input, list):
            input_objs = [obj for pyoObj in input for obj in pyoObj.getBaseObjects()]
            self._linked_objects = input
        else:
            input_objs = input.getBaseObjects()
            self._linked_objects = [input]
        input_len = len(input_objs)
        if voices < 1:
            voices = 1
            num = input_len
        elif voices > input_len and voices > lmax:
            num = voices
        elif lmax > input_len:
            num = lmax
        else:
            num = input_len
        sub_lists = []
        for i in range(voices):
            sub_lists.append([])
        for i in range(num):
            obj = input_objs[i % input_len]
            sub_lists[i % voices].append(obj)
        self._base_objs = [Mix_base(l, wrap(mul, i), wrap(add, i)) for i, l in enumerate(sub_lists)]
        self._init_play()


class Dummy(PyoObject):
    """
    Dummy object used to perform arithmetics on PyoObject.

    The user should never instantiate an object of this class.

    :Parent: :py:class:`PyoObject`

    :Args:

        objs_list: list of audio Stream objects
            List of Stream objects return by the PyoObject hidden method
            getBaseObjects().

    .. note::

        Multiplication, addition, division and substraction don't changed
        the PyoObject on which the operation is performed. A dummy object
        is created, which is just a copy of the audio Streams of the object,
        and the operation is applied on the Dummy, leaving the original
        object unchanged. This lets the user performs multiple different
        arithmetic operations on an object without conficts. Here, `b` is
        a Dummy object with `a` as its input with a `mul` attribute of 0.5.
        attribute:

        >>> a = Sine()
        >>> b = a * .5
        >>> print(a)
        <pyo.lib.input.Sine object at 0x11fd610>
        >>> print(b)
        <pyo.lib._core.Dummy object at 0x11fd710>

    >>> s = Server().boot()
    >>> s.start()
    >>> m = Metro(time=0.25).play()
    >>> p = TrigChoice(m, choice=[midiToHz(n) for n in [60,62,65,67,69]])
    >>> a = SineLoop(p, feedback=.05, mul=.1).mix(2).out()
    >>> b = SineLoop(p*1.253, feedback=.05, mul=.06).mix(2).out()
    >>> c = SineLoop(p*1.497, feedback=.05, mul=.03).mix(2).out()

    """

    def __init__(self, objs_list):
        PyoObject.__init__(self)
        self._objs_list = objs_list
        tmp_list = []
        for x in objs_list:
            if isinstance(x, Dummy):
                tmp_list.extend(x.getBaseObjects())
            else:
                tmp_list.append(x)
        self._base_objs = tmp_list

class ArithmeticDummy(PyoObject):
    def __init__(self, objs_list):
        PyoObject.__init__(self)
        self._objs_list = objs_list
        tmp_list = []
        for x in objs_list:
            if isinstance(x, Dummy):
                tmp_list.extend(x.getBaseObjects())
            else:
                tmp_list.append(x)
        self._base_objs = tmp_list

    def __del__(self):
        try:
            if sys.getrefcount(self._base_objs[0]) >= 2:
                [obj.decref() for obj in self._base_objs]
        except:
            pass

class InputFader(PyoObject):
    """
    Audio streams crossfader.

    :Args:

        input: PyoObject
            Input signal.

    .. note::

        The setInput method, available to object with `input` attribute,
        uses an InputFader object internally to perform crossfade between
        the old and the new audio input assigned to the object.

    >>> s = Server().boot()
    >>> s.start()
    >>> a = SineLoop([449,450], feedback=0.05, mul=.2)
    >>> b = SineLoop([650,651], feedback=0.05, mul=.2)
    >>> c = InputFader(a).out()
    >>> # to created a crossfade, assign a new audio input:
    >>> c.setInput(b, fadetime=5)

    """

    def __init__(self, input):
        pyoArgsAssert(self, "o", input)
        PyoObject.__init__(self)
        self._input = input
        input, lmax = convertArgsToLists(input)
        self._base_objs = [InputFader_base(wrap(input, i)) for i in range(lmax)]
        self._init_play()

    def setInput(self, x, fadetime=0.05):
        """
        Replace the `input` attribute.

        :Args:

            x: PyoObject
                New signal to process.
            fadetime: float, optional
                Crossfade time between old and new input. Defaults to 0.05.

        """
        pyoArgsAssert(self, "oN", x, fadetime)
        self._input = x
        x, _ = convertArgsToLists(x)
        [obj.setInput(wrap(x, i), fadetime) for i, obj in enumerate(self._base_objs)]

    @property
    def input(self):
        """PyoObject. Input signal."""
        return self._input

    @input.setter
    def input(self, x):
        self.setInput(x)


class Sig(PyoObject):
    """
    Convert numeric value to PyoObject signal.

    :Parent: :py:class:`PyoObject`

    :Args:

        value: float or PyoObject
            Numerical value to convert.

    >>> import random
    >>> s = Server().boot()
    >>> s.start()
    >>> fr = Sig(value=400)
    >>> p = Port(fr, risetime=0.001, falltime=0.001)
    >>> a = SineLoop(freq=p, feedback=0.08, mul=.3).out()
    >>> b = SineLoop(freq=p*1.005, feedback=0.08, mul=.3).out(1)
    >>> def pick_new_freq():
    ...     fr.value = random.randrange(300,601,50)
    >>> pat = Pattern(function=pick_new_freq, time=0.5).play()

    """

    def __init__(self, value, mul=1, add=0):
        pyoArgsAssert(self, "OOO", value, mul, add)
        PyoObject.__init__(self, mul, add)
        self._value = value
        value, mul, add, lmax = convertArgsToLists(value, mul, add)
        self._base_objs = [Sig_base(wrap(value, i), wrap(mul, i), wrap(add, i)) for i in range(lmax)]
        self._init_play()

    def setValue(self, x):
        """
        Changes the value of the signal stream.

        :Args:

            x: float or PyoObject
                Numerical value to convert.

        """
        pyoArgsAssert(self, "O", x)
        self._value = x
        x, _ = convertArgsToLists(x)
        [obj.setValue(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def ctrl(self, map_list=None, title=None, wxnoserver=False):
        self._map_list = [SLMap(0, 1, "lin", "value", self._value)]
        PyoObject.ctrl(self, map_list, title, wxnoserver)

    @property
    def value(self):
        """float or PyoObject. Numerical value to convert."""
        return self._value

    @value.setter
    def value(self, x):
        self.setValue(x)


class VarPort(PyoObject):
    """
    Convert numeric value to PyoObject signal with portamento.

    When `value` attribute is changed, a smoothed ramp is applied from the
    current value to the new value. If a callback is provided as `function`
    argument, it will be called at the end of the line.

    :Parent: :py:class:`PyoObject`

    :Args:

        value: float
            Numerical target value to reach as an audio stream.
        time: float, optional
            Ramp time, in seconds, to reach the new value. Defaults to 0.025.
        init: float, optional
            Initial value of the internal memory. Defaults to 0.
        function: Python callable, optional
            If provided, it will be called at the end of the line.
            Defaults to None.
        arg: any Python object, optional
            Optional argument sent to the function called at the end of the line.
            Defaults to None.

    .. note::

        The out() method is bypassed. VarPort's signal can not be sent to
        audio outs.

    >>> s = Server().boot()
    >>> s.start()
    >>> def callback(arg):
    ...     print("end of line")
    ...     print(arg)
    ...
    >>> fr = VarPort(value=500, time=2, init=250, function=callback, arg="YEP!")
    >>> a = SineLoop(freq=[fr,fr*1.01], feedback=0.05, mul=.2).out()

    """

    def __init__(self, value, time=0.025, init=0.0, function=None, arg=None, mul=1, add=0):
        pyoArgsAssert(self, "nnnczOO", value, time, init, function, arg, mul, add)
        PyoObject.__init__(self, mul, add)
        self._value = value
        self._time = time
        self._function = getWeakMethodRef(function)
        value, time, init, function, arg, mul, add, lmax = convertArgsToLists(
            value, time, init, function, arg, mul, add
        )
        self._base_objs = [
            VarPort_base(
                wrap(value, i),
                wrap(time, i),
                wrap(init, i),
                WeakMethod(wrap(function, i)),
                wrap(arg, i),
                wrap(mul, i),
                wrap(add, i),
            )
            for i in range(lmax)
        ]
        self._init_play()

    def setValue(self, x):
        """
        Changes the target value of the signal stream.

        :Args:

            x: float
                Numerical value to convert.

        """
        pyoArgsAssert(self, "n", x)
        self._value = x
        x, _ = convertArgsToLists(x)
        [obj.setValue(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def setTime(self, x):
        """
        Changes the ramp time of the object.

        :Args:

            x: float
                New ramp time.

        """
        pyoArgsAssert(self, "n", x)
        self._time = x
        x, _ = convertArgsToLists(x)
        [obj.setTime(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def setFunction(self, x):
        """
        Replace the `function` attribute.

        :Args:

            x: Python function
                new `function` attribute.

        """
        pyoArgsAssert(self, "c", x)
        self._function = getWeakMethodRef(x)
        x, _ = convertArgsToLists(x)
        [obj.setFunction(WeakMethod(wrap(x, i))) for i, obj in enumerate(self._base_objs)]

    @property
    def value(self):
        """float. Numerical target value."""
        return self._value

    @value.setter
    def value(self, x):
        self.setValue(x)

    @property
    def time(self):
        """float. Ramp time."""
        return self._time

    @time.setter
    def time(self, x):
        self.setTime(x)

    @property
    def function(self):
        """Python callable. Function to be called."""
        return self._function

    @function.setter
    def function(self, x):
        self.setFunction(x)


class Pow(PyoObject):
    """
    Performs a power function on audio signal.

    :Parent: :py:class:`PyoObject`

    :Args:

        base: float or PyoObject, optional
            Base composant. Defaults to 10.
        exponent: float or PyoObject, optional
            Exponent composant. Defaults to 1.

    >>> s = Server().boot()
    >>> s.start()
    >>> # Exponential amplitude envelope
    >>> a = LFO(freq=1, type=3, mul=0.5, add=0.5)
    >>> b = Pow(Clip(a, 0, 1), 4, mul=.3)
    >>> c = SineLoop(freq=[300,301], feedback=0.05, mul=b).out()

    """

    def __init__(self, base=10, exponent=1, mul=1, add=0):
        pyoArgsAssert(self, "OOOO", base, exponent, mul, add)
        PyoObject.__init__(self, mul, add)
        self._base = base
        self._exponent = exponent
        base, exponent, mul, add, lmax = convertArgsToLists(base, exponent, mul, add)
        self._base_objs = [
            M_Pow_base(wrap(base, i), wrap(exponent, i), wrap(mul, i), wrap(add, i)) for i in range(lmax)
        ]
        self._init_play()

    def setBase(self, x):
        """
        Replace the `base` attribute.

        :Args:

            x: float or PyoObject
                new `base` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._base = x
        x, _ = convertArgsToLists(x)
        [obj.setBase(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def setExponent(self, x):
        """
        Replace the `exponent` attribute.

        :Args:

            x: float or PyoObject
                new `exponent` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._exponent = x
        x, _ = convertArgsToLists(x)
        [obj.setExponent(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    @property
    def base(self):
        """float or PyoObject. Base composant."""
        return self._base

    @base.setter
    def base(self, x):
        self.setBase(x)

    @property
    def exponent(self):
        """float or PyoObject. Exponent composant."""
        return self._exponent

    @exponent.setter
    def exponent(self, x):
        self.setExponent(x)


class Wrap(PyoObject):
    """
    Wraps-around the signal that exceeds the `min` and `max` thresholds.

    This object is useful for table indexing, phase shifting or for
    clipping and modeling an audio signal.

    :Parent: :py:class:`PyoObject`

    :Args:

        input: PyoObject
            Input signal to process.
        min: float or PyoObject, optional
            Minimum possible value. Defaults to 0.
        max: float or PyoObject, optional
            Maximum possible value. Defaults to 1.

    .. note::

        If `min` is higher than `max`, then the output will be the average
        of the two.

    .. seealso::

        :py:class:`Clip`, :py:class:`Mirror`

    >>> s = Server().boot()
    >>> s.start()
    >>> # Time-varying overlaping envelopes
    >>> env = HannTable()
    >>> lff = Sine(.5, mul=3, add=4)
    >>> ph1 = Phasor(lff)
    >>> ph2 = Wrap(ph1+0.5, min=0, max=1)
    >>> amp1 = Pointer(env, ph1, mul=.25)
    >>> amp2 = Pointer(env, ph2, mul=.25)
    >>> a = SineLoop(250, feedback=.1, mul=amp1).out()
    >>> b = SineLoop(300, feedback=.1, mul=amp2).out(1)

    """

    def __init__(self, input, min=0.0, max=1.0, mul=1, add=0):
        pyoArgsAssert(self, "oOOOO", input, min, max, mul, add)
        PyoObject.__init__(self, mul, add)
        self._input = input
        self._min = min
        self._max = max
        self._in_fader = InputFader(input)
        in_fader, min, max, mul, add, lmax = convertArgsToLists(self._in_fader, min, max, mul, add)
        self._base_objs = [
            Wrap_base(wrap(in_fader, i), wrap(min, i), wrap(max, i), wrap(mul, i), wrap(add, i)) for i in range(lmax)
        ]
        self._init_play()

    def setInput(self, x, fadetime=0.05):
        """
        Replace the `input` attribute.

        :Args:

            x: PyoObject
                New signal to process.
            fadetime: float, optional
                Crossfade time between old and new input. Defaults to 0.05.

        """
        pyoArgsAssert(self, "oN", x, fadetime)
        self._input = x
        self._in_fader.setInput(x, fadetime)

    def setMin(self, x):
        """
        Replace the `min` attribute.

        :Args:

            x: float or PyoObject
                New `min` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._min = x
        x, _ = convertArgsToLists(x)
        [obj.setMin(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def setMax(self, x):
        """
        Replace the `max` attribute.

        :Args:

            x: float or PyoObject
                New `max` attribute.

        """
        pyoArgsAssert(self, "O", x)
        self._max = x
        x, _ = convertArgsToLists(x)
        [obj.setMax(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def ctrl(self, map_list=None, title=None, wxnoserver=False):
        self._map_list = [
            SLMap(0.0, 1.0, "lin", "min", self._min),
            SLMap(0.0, 1.0, "lin", "max", self._max),
            SLMapMul(self._mul),
        ]
        PyoObject.ctrl(self, map_list, title, wxnoserver)

    @property
    def input(self):
        """PyoObject. Input signal to process."""
        return self._input

    @input.setter
    def input(self, x):
        self.setInput(x)

    @property
    def min(self):
        """float or PyoObject. Minimum possible value."""
        return self._min

    @min.setter
    def min(self, x):
        self.setMin(x)

    @property
    def max(self):
        """float or PyoObject. Maximum possible value."""
        return self._max

    @max.setter
    def max(self, x):
        self.setMax(x)


class Compare(PyoObject):
    """
    Comparison object.

    Compare evaluates a comparison between a PyoObject and a number or
    between two PyoObjects and outputs 1.0, as audio stream, if the
    comparison is true, otherwise outputs 0.0.

    :Parent: :py:class:`PyoObject`

    :Args:

        input: PyoObject
            Input signal.
        comp: float or PyoObject
            comparison signal.
        mode: string, optional
            Comparison operator as a string. Allowed operator are "<", "<=",
            ">", ">=", "==", "!=". Default to "<".

    >>> s = Server().boot()
    >>> s.start()
    >>> a = SineLoop(freq=[199,200], feedback=.1, mul=.2)
    >>> b = SineLoop(freq=[149,150], feedback=.1, mul=.2)
    >>> ph = Phasor(freq=1)
    >>> ch = Compare(input=ph, comp=0.5, mode="<=")
    >>> out = Selector(inputs=[a,b], voice=Port(ch)).out()

    """

    def __init__(self, input, comp, mode="<", mul=1, add=0):
        pyoArgsAssert(self, "oOsOO", input, comp, mode, mul, add)
        PyoObject.__init__(self, mul, add)
        self._input = input
        self._comp = comp
        self._mode = mode
        self._in_fader = InputFader(input)
        self.comp_dict = {"<": 0, "<=": 1, ">": 2, ">=": 3, "==": 4, "!=": 5}
        in_fader, comp, mode, mul, add, lmax = convertArgsToLists(self._in_fader, comp, mode, mul, add)
        self._base_objs = [
            Compare_base(wrap(in_fader, i), wrap(comp, i), self.comp_dict[wrap(mode, i)], wrap(mul, i), wrap(add, i))
            for i in range(lmax)
        ]
        self._init_play()

    def out(self, chnl=0, inc=1, dur=0, delay=0):
        return self.play(dur, delay)

    def setInput(self, x, fadetime=0.05):
        """
        Replace the `input` attribute.

        :Args:

            x: PyoObject
                New signal to process.
            fadetime: float, optional
                Crossfade time between old and new input. Default to 0.05.

        """
        pyoArgsAssert(self, "oN", x, fadetime)
        self._input = x
        self._in_fader.setInput(x, fadetime)

    def setComp(self, x):
        """
        Replace the `comp` attribute.

        :Args:

            x: float or PyoObject
                New comparison signal.

        """
        pyoArgsAssert(self, "O", x)
        self._comp = x
        x, _ = convertArgsToLists(x)
        [obj.setComp(wrap(x, i)) for i, obj in enumerate(self._base_objs)]

    def setMode(self, x):
        """
        Replace the `mode` attribute.

        Allowed operator are "<", "<=", ">", ">=", "==", "!=".

        :Args:

            x: string
                New `mode` attribute.

        """
        pyoArgsAssert(self, "s", x)
        self._mode = x
        x, _ = convertArgsToLists(x)
        [obj.setMode(self.comp_dict[wrap(x, i)]) for i, obj in enumerate(self._base_objs)]

    @property
    def input(self):
        """PyoObject. Input signal."""
        return self._input

    @input.setter
    def input(self, x):
        self.setInput(x)

    @property
    def comp(self):
        """PyoObject. Comparison signal."""
        return self._comp

    @comp.setter
    def comp(self, x):
        self.setComp(x)

    @property
    def mode(self):
        """string. Comparison operator."""
        return self._mode

    @mode.setter
    def mode(self, x):
        self.setMode(x)