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
//! Use the [**Signal** trait](./trait.Signal.html) for working with **Iterator**s that yield
//! **Frame**s. To complement the **Iterator** trait, **Signal** provides methods for adding,
//! scaling, offsetting, multiplying, clipping and generating frame iterators and more.
//!
//! You may also find a series of **Signal** source functions, including:
//!
//! - [equilibrium](./fn.equilibrium.html) for generating "silent" frames.
//! - [phase](./fn.phase.html) for a stepping phase, useful for oscillators.
//! - [sine](./fn.sine.html) for generating a sine waveform.
//! - [saw](./fn.saw.html) for generating a sawtooth waveform.
//! - [square](./fn.square.html) for generating a square waveform.
//! - [noise](./fn.noise.html) for generating a noise waveform.
//! - [noise_simplex](./fn.noise_simplex.html) for generating a 1D simplex noise waveform.
//! - [gen](./fn.gen.html) for generating frames of type F from some `Fn() -> F`.
//! - [gen_mut](./fn.gen_mut.html) for generating frames of type F from some `FnMut() -> F`.
//! - [from_interleaved_samples](./fn.from_interleaved_samples.html) for converting an iterator yielding samples to an
//! iterator yielding frames.
//!
//! Working with **Signal**s allows for easy, readable creation of rich and complex DSP graphs with
//! a simple and familiar API.

use {Duplex, Frame, Sample, Vec, Rc, VecDeque};
use rate;
use core;


/// Implement `Signal` for all `Iterator`s that yield `Frame`s.
impl<I> Signal for I where I: Iterator, I::Item: Frame {}

/// A trait that allows us to treat `Iterator`s that yield `Frame`s as a multi-channel PCM signal.
///
/// For example, `Signal` allows us to add two signals, modulate a signal's amplitude by another
/// signal, scale a signals amplitude and much more.
///
/// `Signal` has a blanket implementation for all `Iterator`s whose `Item` associated types
/// implement `Frame`.
pub trait Signal: Iterator + Sized
    where Self::Item: Frame,
{

    /// Provides an iterator that yields the sum of the frames yielded by both `other` and `self`
    /// in lock-step.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let a = [[0.2], [-0.6], [0.5]];
    ///     let b = [[0.2], [0.1], [-0.8]];
    ///     let a_signal = a.iter().cloned();
    ///     let b_signal = b.iter().cloned();
    ///     let added: Vec<[f32; 1]> = a_signal.add_amp(b_signal).collect();
    ///     assert_eq!(added, vec![[0.4], [-0.5], [-0.3]]);
    /// }
    /// ```
    #[inline]
    fn add_amp<S>(self, other: S) -> AddAmp<Self, S>
        where S: Signal,
              S::Item: Frame<Sample=<<Self::Item as Frame>::Sample as Sample>::Signed,
                             NumChannels=<Self::Item as Frame>::NumChannels>,
    {
        AddAmp {
            a: self,
            b: other,
        }
    }

    /// Provides an iterator that yields the product of the frames yielded by both `other` and
    /// `self` in lock-step.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let a = [[0.25], [-0.8], [-0.5]];
    ///     let b = [[0.2], [0.5], [0.8]];
    ///     let a_signal = a.iter().cloned();
    ///     let b_signal = b.iter().cloned();
    ///     let added: Vec<_> = a_signal.mul_amp(b_signal).collect();
    ///     assert_eq!(added, vec![[0.05], [-0.4], [-0.4]]);
    /// }
    /// ```
    #[inline]
    fn mul_amp<S>(self, other: S) -> MulAmp<Self, S>
        where S: Signal,
              S::Item: Frame<Sample=<<Self::Item as Frame>::Sample as Sample>::Float,
                             NumChannels=<Self::Item as Frame>::NumChannels>,
    {
        MulAmp {
            a: self,
            b: other,
        }
    }

    /// Provides an iterator that offsets the amplitude of every channel in each frame of the
    /// signal by some sample value and yields the resulting frames.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.25, 0.4], [-0.2, -0.5]];
    ///     let signal = frames.iter().cloned();
    ///     let offset: Vec<[f32; 2]> = signal.offset_amp(0.5).collect();
    ///     assert_eq!(offset, vec![[0.75, 0.9], [0.3, 0.0]]);
    /// }
    /// ```
    #[inline]
    fn offset_amp(self, offset: <<Self::Item as Frame>::Sample as Sample>::Signed)
        -> OffsetAmp<Self>
    {
        OffsetAmp {
            signal: self,
            offset: offset,
        }
    }

    /// Produces an `Iterator` that scales the amplitude of the sample of each channel in every
    /// `Frame` yielded by `self` by the given amplitude.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.2], [-0.5], [-0.4], [0.3]];
    ///     let signal = frames.iter().cloned();
    ///     let scaled: Vec<[f32; 1]> = signal.scale_amp(2.0).collect();
    ///     assert_eq!(scaled, vec![[0.4], [-1.0], [-0.8], [0.6]]);
    /// }
    /// ```
    #[inline]
    fn scale_amp(self, amp: <<Self::Item as Frame>::Sample as Sample>::Float) -> ScaleAmp<Self> {
        ScaleAmp {
            signal: self,
            amp: amp,
        }
    }

    /// Produces an `Iterator` that offsets the amplitude of every `Frame` in `self` by the
    /// respective amplitudes in each channel of the given `amp_frame`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.5, 0.3], [-0.25, 0.9]];
    ///     let mut signal = frames.iter().cloned().offset_amp_per_channel([0.25, -0.5]);
    ///     assert_eq!(signal.next().unwrap(), [0.75, -0.2]);
    ///     assert_eq!(signal.next().unwrap(), [0.0, 0.4]);
    /// }
    /// ```
    #[inline]
    fn offset_amp_per_channel<F>(self, amp_frame: F) -> OffsetAmpPerChannel<Self, F>
        where F: Frame<Sample=<<Self::Item as Frame>::Sample as Sample>::Signed,
                       NumChannels=<Self::Item as Frame>::NumChannels>,
    {
        OffsetAmpPerChannel {
            signal: self,
            amp_frame: amp_frame,
        }
    }

    /// Produces an `Iterator` that scales the amplitude of every `Frame` in `self` by the
    /// respective amplitudes in each channel of the given `amp_frame`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.2, -0.5], [-0.4, 0.3]];
    ///     let mut signal = frames.iter().cloned().scale_amp_per_channel([0.5, 2.0]);
    ///     assert_eq!(signal.next().unwrap(), [0.1, -1.0]);
    ///     assert_eq!(signal.next().unwrap(), [-0.2, 0.6]);
    /// }
    /// ```
    #[inline]
    fn scale_amp_per_channel<F>(self, amp_frame: F) -> ScaleAmpPerChannel<Self, F>
        where F: Frame<Sample=<<Self::Item as Frame>::Sample as Sample>::Float,
                       NumChannels=<Self::Item as Frame>::NumChannels>,
    {
        ScaleAmpPerChannel {
            signal: self,
            amp_frame: amp_frame,
        }
    }

    /// Multiplies the rate at which frames of `self` are yielded by the given `signal`.
    ///
    /// This happens by wrapping `self` in a `rate::Converter` and calling `set_playback_hz_scale`
    /// with the value yielded by `signal`
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
    ///     let mul = [1.0, 1.0, 0.5, 0.5, 0.5, 0.5];
    ///     let frames: Vec<_> = foo.iter().cloned().mul_hz(mul.iter().cloned()).collect();
    ///     assert_eq!(&frames[..], &[[0.0], [1.0], [0.0], [-0.5], [-1.0]][..]);
    /// }
    /// ```
    fn mul_hz<I>(self, mul_per_frame: I) -> MulHz<Self, I>
        where I: Iterator<Item=f64>,
    {
        MulHz {
            signal: rate::Converter::scale_playback_hz(self, 1.0),
            mul_per_frame: mul_per_frame,
        }
    }

    /// Converts the rate at which frames of the `Signal` are yielded using interpolation.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
    ///     let frames: Vec<_> = foo.iter().cloned().from_hz_to_hz(1.0, 2.0).collect();
    ///     assert_eq!(&frames[..], &[[0.0], [0.5], [1.0], [0.5], [0.0], [-0.5], [-1.0]][..]);
    /// }
    /// ```
    fn from_hz_to_hz(self, source_hz: f64, target_hz: f64) -> rate::Converter<Self> {
        rate::Converter::from_hz_to_hz(self, source_hz, target_hz)
    }

    /// Multiplies the rate at which frames of the `Signal` are yielded by the given value.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let foo = [[0.0], [1.0], [0.0], [-1.0]];
    ///     let frames: Vec<_> = foo.iter().cloned().scale_hz(0.5).collect();
    ///     assert_eq!(&frames[..], &[[0.0], [0.5], [1.0], [0.5], [0.0], [-0.5], [-1.0]][..]);
    /// }
    /// ```
    fn scale_hz(self, multi: f64) -> rate::Converter<Self> {
        rate::Converter::scale_playback_hz(self, multi)
    }

    /// Delays the `Signal` by the given number of frames.
    ///
    /// The delay is performed by yielding `Frame::equilibrium()` `n_frames` times before
    /// continuing to yield frames from `signal`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.2], [0.4]];
    ///     let delayed: Vec<_> = frames.iter().cloned().delay(2).collect();
    ///     assert_eq!(delayed, vec![[0.0], [0.0], [0.2], [0.4]]);
    /// }
    /// ```
    fn delay(self, n_frames: usize) -> Delay<Self> {
        Delay {
            signal: self,
            n_frames: n_frames,
        }
    }

    /// Converts a `Iterator` yielding `Frame`s into an `Iterator` yielding `Sample`s.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.1, 0.2], [0.3, 0.4]];
    ///     let samples: Vec<_> = frames.iter().cloned().to_samples().collect();
    ///     assert_eq!(samples, vec![0.1, 0.2, 0.3, 0.4]);
    /// }
    /// ```
    fn to_samples(self) -> ToSamples<Self> {
        ToSamples {
            signal: self,
            current_frame: None,
        }
    }

    /// Clips the amplitude of each channel in each `Frame` yielded by `self` to the given
    /// threshold amplitude.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[1.2, 0.8], [-0.7, -1.4]];
    ///     let clipped: Vec<_> = frames.iter().cloned().clip_amp(0.9).collect();
    ///     assert_eq!(clipped, vec![[0.9, 0.8], [-0.7, -0.9]]);
    /// }
    /// ```
    fn clip_amp(self, thresh: <<Self::Item as Frame>::Sample as Sample>::Signed) -> ClipAmp<Self> {
        ClipAmp {
            signal: self,
            thresh: thresh,
        }
    }

    /// Moves the `Signal` into a `Bus` from which its output may be divided into multiple other
    /// `Signal`s in the form of `Output`s.
    ///
    /// This method allows to create more complex directed acyclic graph structures that
    /// incorporate concepts like sends, side-chaining, etc, rather than being restricted to tree
    /// structures where signals can only ever be joined but never divided.
    ///
    /// Note: When using multiple `Output`s in this fashion, you will need to be sure to pull the
    /// frames from each `Output` in sync (whether per frame or per buffer). This is because when
    /// output A requests `Frame`s before output B, those frames mjust remain available for output
    /// B and in turn must be stored in an intermediary ring buffer.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.1], [0.2], [0.3]];
    ///     let bus = frames.iter().cloned().bus();
    ///     let mut a = bus.send();
    ///     let mut b = bus.send();
    ///     assert_eq!(a.collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
    ///     assert_eq!(b.collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
    /// }
    /// ```
    fn bus(self) -> Bus<Self> {
        Bus {
            node: Rc::new(core::cell::RefCell::new(SharedNode {
                signal: self,
                buffers: vec![VecDeque::new()],
            })),
        }
    }

}


///// Signal Types


/// An iterator that endlessly yields `Frame`s of type `F` at equilibrium.
#[derive(Clone)]
pub struct Equilibrium<F> {
    frame: core::marker::PhantomData<F>,
}

/// A signal that generates frames using the given function.
#[derive(Clone)]
pub struct Gen<G, F> {
    gen: G,
    frame: core::marker::PhantomData<F>,
}

/// A signal that generates frames using the given function which may mutate some state.
#[derive(Clone)]
pub struct GenMut<G, F> {
    gen_mut: G,
    frame: core::marker::PhantomData<F>,
}

/// An iterator that converts an iterator of `Sample`s to an iterator of `Frame`s.
#[derive(Clone)]
pub struct FromInterleavedSamples<I, F>
    where I: Iterator,
          I::Item: Sample,
          F: Frame<Sample=I::Item>,
{
    samples: I,
    frame: core::marker::PhantomData<F>,
}

/// The rate at which phrase a **Signal** is sampled.
#[derive(Copy, Clone, Debug, PartialEq)]
pub struct Rate {
    hz: f64,
}

/// A constant phase step size.
#[derive(Clone)]
pub struct ConstHz {
    step: f64,
}

/// An iterator that yields the step size for a phase.
#[derive(Clone)]
pub struct Hz<I> {
    hz: I,
    last_step_size: f64,
    rate: Rate,
}


/// An iterator that yields a phase, useful for waveforms like Sine or Saw.
#[derive(Clone)]
pub struct Phase<S> {
    step: S,
    next: f64,
}

/// A sine wave signal generator.
#[derive(Clone)]
pub struct Sine<S> {
    phase: Phase<S>,
}

/// A saw wave signal generator.
#[derive(Clone)]
pub struct Saw<S> {
    phase: Phase<S>,
}

/// A square wave signal generator.
#[derive(Clone)]
pub struct Square<S> {
    phase: Phase<S>,
}

/// A noise signal generator.
#[derive(Clone)]
pub struct Noise {
    seed: u64,
}

/// A 1D simplex-noise generator.
#[derive(Clone)]
pub struct NoiseSimplex<S> {
    phase: Phase<S>,
}

/// An iterator that yields the sum of the frames yielded by both `other` and `self` in lock-step.
#[derive(Clone)]
pub struct AddAmp<A, B> {
    a: A,
    b: B,
}

/// An iterator that yields the product of the frames yielded by both `other` and `self` in
/// lock-step.
#[derive(Clone)]
pub struct MulAmp<A, B> {
    a: A,
    b: B,
}

/// Provides an iterator that offsets the amplitude of every channel in each frame of the
/// signal by some sample value and yields the resulting frames.
#[derive(Clone)]
pub struct OffsetAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    signal: S,
    offset: <<S::Item as Frame>::Sample as Sample>::Signed,
}

/// An `Iterator` that scales the amplitude of the sample of each channel in every `Frame` yielded
/// by `self` by the given amplitude.
#[derive(Clone)]
pub struct ScaleAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    signal: S,
    amp: <<S::Item as Frame>::Sample as Sample>::Float,
}

/// An `Iterator` that scales the amplitude of every `Frame` in `self` by the respective amplitudes
/// in each channel of the given `amp` `Frame`.
#[derive(Clone)]
pub struct OffsetAmpPerChannel<S, F> {
    signal: S,
    amp_frame: F,
}

/// An `Iterator` that scales the amplitude of every `Frame` in `self` by the respective amplitudes
/// in each channel of the given `amp` `Frame`.
#[derive(Clone)]
pub struct ScaleAmpPerChannel<S, F> {
    signal: S,
    amp_frame: F,
}

/// Multiplies the rate at which frames of `self` are yielded by the given `signal`.
///
/// This happens by wrapping `self` in a `rate::Converter` and calling `set_playback_hz_scale`
/// with the value yielded by `signal`
#[derive(Clone)]
pub struct MulHz<S, M>
    where S: Signal,
          S::Item: Frame,
{
    signal: rate::Converter<S>,
    mul_per_frame: M,
}

/// Delays the `signal` by the given number of frames.
///
/// The delay is performed by yielding `Frame::equilibrium()` `n_frames` times before
/// continuing to yield frames from `signal`.
#[derive(Clone)]
pub struct Delay<S> {
    signal: S,
    n_frames: usize,
}

/// Converts a `Signal` to an `Iterator` yielding `Sample`s of the signal.
pub struct ToSamples<S>
    where S: Signal,
          S::Item: Frame,
{
    signal: S,
    current_frame: Option<<S::Item as Frame>::Channels>,
}

/// Clips samples in each frame yielded by `signal` to the given threshhold amplitude.
#[derive(Clone)]
pub struct ClipAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    signal: S,
    thresh: <<S::Item as Frame>::Sample as Sample>::Signed,
}

/// A type which allows for `send`ing a single `Signal` to multiple outputs.
///
/// This type manages
pub struct Bus<S>
    where S: Signal,
          S::Item: Frame,
{
    node: Rc<core::cell::RefCell<SharedNode<S>>>,
}

/// The data shared between each `Output`.
struct SharedNode<S>
    where S: Signal,
          S::Item: Frame,
{
    signal: S,
    buffers: Vec<VecDeque<S::Item>>,
}

/// An output node to which some signal `S` is `Output`ing its frames.
///
/// It may be more accurate to say that the `Output` "pull"s frames from the signal.
pub struct Output<S>
    where S: Signal,
          S::Item: Frame,
{
    idx: usize,
    node: Rc<core::cell::RefCell<SharedNode<S>>>,
}


///// Signal Constructors


/// Provides an iterator that endlessly yields `Frame`s of type `F` at equilibrium.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::Signal;
///
/// fn main() {
///     let equilibrium: Vec<[f32; 1]> = sample::signal::equilibrium().take(4).collect();
///     assert_eq!(equilibrium, vec![[0.0], [0.0], [0.0], [0.0]]);
///
///     let equilibrium: Vec<[u8; 2]> = sample::signal::equilibrium().take(3).collect();
///     assert_eq!(equilibrium, vec![[128, 128], [128, 128], [128, 128]]);
/// }
/// ```
pub fn equilibrium<F>() -> Equilibrium<F>
    where F: Frame,
{
    Equilibrium { frame: core::marker::PhantomData }
}


/// A signal that generates frames using the given function.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// fn main() {
///     let mut frames = sample::signal::gen(|| [0.5]);
///     assert_eq!(frames.next(), Some([0.5]));
///     assert_eq!(frames.next(), Some([0.5]));
/// }
/// ```
pub fn gen<G, F>(gen: G) -> Gen<G, F>
    where G: Fn() -> F,
          F: Frame,
{
    Gen {
        gen: gen,
        frame: core::marker::PhantomData,
    }
}


/// A signal that generates frames using the given function which may mutate some state.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// fn main() {
///     let mut f = [0.0];
///     let mut frames = sample::signal::gen_mut(|| {
///         let r = f;
///         f[0] += 0.1;
///         r
///     });
///     assert_eq!(frames.next(), Some([0.0]));
///     assert_eq!(frames.next(), Some([0.1]));
///     assert_eq!(frames.next(), Some([0.2]));
/// }
/// ```
pub fn gen_mut<G, F>(gen_mut: G) -> GenMut<G, F>
    where G: FnMut() -> F,
          F: Frame,
{
    GenMut {
        gen_mut: gen_mut,
        frame: core::marker::PhantomData,
    }
}


/// An iterator that converts the given `Iterator` yielding `Sample`s to a `Signal` yielding frames
/// of type `F`.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     let foo = [0, 1, 2, 3];
///     let mut signal = signal::from_interleaved_samples::<_, [i32; 2]>(foo.iter().cloned());
///     assert_eq!(signal.next(), Some([0, 1]));
///     assert_eq!(signal.next(), Some([2, 3]));
///     assert_eq!(signal.next(), None);
///
///     let bar = [0, 1, 2];
///     let mut signal = signal::from_interleaved_samples::<_, [i32; 2]>(bar.iter().cloned());
///     assert_eq!(signal.next(), Some([0, 1]));
///     assert_eq!(signal.next(), None);
/// }
/// ```
pub fn from_interleaved_samples<I, F>(samples: I) -> FromInterleavedSamples<I, F>
    where I: Iterator,
          I::Item: Sample,
          F: Frame<Sample=I::Item>,
{
    FromInterleavedSamples {
        samples: samples,
        frame: core::marker::PhantomData,
    }
}


/// Creates a `Phase` that continuously steps forward by the given `step` size yielder.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     let step = signal::rate(4.0).const_hz(1.0);
///     // Note that this is the same as `step.phase()`, a composable alternative.
///     let mut phase = signal::phase(step);
///     assert_eq!(phase.next(), Some([0.0]));
///     assert_eq!(phase.next(), Some([0.25]));
///     assert_eq!(phase.next(), Some([0.5]));
///     assert_eq!(phase.next(), Some([0.75]));
///     assert_eq!(phase.next(), Some([0.0]));
///     assert_eq!(phase.next(), Some([0.25]));
/// }
/// ```
pub fn phase<S>(step: S) -> Phase<S>
    where S: Step,
{
    Phase {
        step: step,
        next: 0.0,
    }
}


/// Creates a frame `Rate` (aka sample rate) representing the rate at which a signal may be
/// sampled.
///
/// This is necessary for composing `Hz` or `ConstHz`, both of which may be used to step forward
/// the `Phase` for some kind of oscillator (i.e. `Sine`, `Saw`, `Square` or `NoiseSimplex`).
/// ```
pub fn rate(hz: f64) -> Rate {
    Rate { hz: hz }
}


/// Produces a `Signal` that yields a sine wave oscillating at the given hz.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     // Generates a sine wave signal at 1hz to be sampled 4 times per second.
///     let mut signal = signal::rate(4.0).const_hz(1.0).sine();
///     assert_eq!(signal.next(), Some([0.0]));
///     assert_eq!(signal.next(), Some([1.0]));
///     signal.next();
///     assert_eq!(signal.next(), Some([-1.0]));
/// }
/// ```
pub fn sine<S>(phase: Phase<S>) -> Sine<S> {
    Sine { phase: phase }
}

/// Produces a `Signal` that yields a saw wave oscillating at the given hz.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     // Generates a saw wave signal at 1hz to be sampled 4 times per second.
///     let mut signal = signal::rate(4.0).const_hz(1.0).saw();
///     assert_eq!(signal.next(), Some([1.0]));
///     assert_eq!(signal.next(), Some([0.5]));
///     assert_eq!(signal.next(), Some([0.0]));
///     assert_eq!(signal.next(), Some([-0.5]));
/// }
/// ```
pub fn saw<S>(phase: Phase<S>) -> Saw<S> {
    Saw { phase: phase }
}

/// Produces a `Signal` that yields a square wave oscillating at the given hz.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     // Generates a square wave signal at 1hz to be sampled 4 times per second.
///     let mut signal = signal::rate(4.0).const_hz(1.0).square();
///     assert_eq!(signal.next(), Some([1.0]));
///     assert_eq!(signal.next(), Some([1.0]));
///     assert_eq!(signal.next(), Some([-1.0]));
///     assert_eq!(signal.next(), Some([-1.0]));
/// }
/// ```
pub fn square<S>(phase: Phase<S>) -> Square<S> {
    Square { phase: phase }
}

/// Produces a `Signal` that yields random values between -1.0..1.0.
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// fn main() {
///     let mut noise = sample::signal::noise(0);
///     for n in noise.take(1_000_000) {
///         assert!(-1.0 <= n[0] && n[0] < 1.0);
///     }
/// }
/// ```
pub fn noise(seed: u64) -> Noise {
    Noise { seed: seed }
}

/// Produces a 1-dimensional simplex noise `Signal`.
///
/// This is sometimes known as the "drunken walk" or "noise walk".
///
/// # Example
///
/// ```rust
/// extern crate sample;
///
/// use sample::signal;
///
/// fn main() {
///     // Creates a simplex noise signal oscillating at 440hz sampled 44_100 times per second.
///     let mut signal = signal::rate(44_100.0).const_hz(440.0).noise_simplex();
///     for n in signal.take(1_000_000) {
///         assert!(-1.0 <= n[0] && n[0] < 1.0);
///     }
/// }
/// ```
pub fn noise_simplex<S>(phase: Phase<S>) -> NoiseSimplex<S> {
    NoiseSimplex { phase: phase }
}


//// Trait Implementations for Signal Types.


impl<F> Iterator for Equilibrium<F>
    where F: Frame,
{
    type Item = F;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some(F::equilibrium())
    }
}

impl<F> DoubleEndedIterator for Equilibrium<F>
    where F: Frame,
{
    #[inline]
    fn next_back(&mut self) -> Option<Self::Item> {
        Some(F::equilibrium())
    }
}


impl<G, F> Iterator for Gen<G, F>
    where G: Fn() -> F,
{
    type Item = F;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some((self.gen)())
    }
}


impl<G, F> Iterator for GenMut<G, F>
    where G: FnMut() -> F,
{
    type Item = F;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some((self.gen_mut)())
    }
}


impl<I, F> Iterator for FromInterleavedSamples<I, F>
    where I: Iterator,
          I::Item: Sample,
          F: Frame<Sample=I::Item>,
{
    type Item = F;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        F::from_samples(&mut self.samples)
    }
}


impl Rate {

    /// Create a `ConstHz` iterator which consistently yields "hz / rate".
    pub fn const_hz(self, hz: f64) -> ConstHz {
        ConstHz { step: hz / self.hz }
    }

    /// Create a variable `hz` some iterator that yields hz and an initial hz.
    ///
    /// The `Hz` iterator yields phase step sizes equal to "hz / rate".
    pub fn hz<I>(self, init: f64, hz: I) -> Hz<I>
        where I: Iterator<Item=f64>,
    {
        Hz {
            hz: hz,
            last_step_size: init / self.hz,
            rate: self,
        }
    }

}

impl<I> Hz<I>
    where I: Iterator<Item=f64>,
{

    /// Construct a `Phase` iterator that, for every `hz` yielded by `self`, yields a phase that is
    /// stepped by `hz / self.rate.hz`.
    #[inline]
    pub fn phase(self) -> Phase<Self> {
        phase(self)
    }

    /// A composable alternative to the `signal::sine` function.
    #[inline]
    pub fn sine(self) -> Sine<Self> {
        self.phase().sine()
    }

    /// A composable alternative to the `signal::saw` function.
    #[inline]
    pub fn saw(self) -> Saw<Self> {
        self.phase().saw()
    }

    /// A composable alternative to the `signal::square` function.
    #[inline]
    pub fn square(self) -> Square<Self> {
        self.phase().square()
    }

    /// A composable alternative to the `signal::noise_simplex` function.
    #[inline]
    pub fn noise_simplex(self) -> NoiseSimplex<Self> {
        self.phase().noise_simplex()
    }

}

impl ConstHz {

    /// Construct a `Phase` iterator that is incremented via the constant step size, `self.step`.
    #[inline]
    pub fn phase(self) -> Phase<Self> {
        phase(self)
    }

    /// A composable alternative to the `signal::sine` function.
    #[inline]
    pub fn sine(self) -> Sine<Self> {
        self.phase().sine()
    }

    /// A composable alternative to the `signal::saw` function.
    #[inline]
    pub fn saw(self) -> Saw<Self> {
        self.phase().saw()
    }

    /// A composable alternative to the `signal::square` function.
    #[inline]
    pub fn square(self) -> Square<Self> {
        self.phase().square()
    }

    /// A composable alternative to the `signal::noise_simplex` function.
    #[inline]
    pub fn noise_simplex(self) -> NoiseSimplex<Self> {
        self.phase().noise_simplex()
    }

}

/// Types that may be used to give a phase step size based on some `hz / sample rate`.
///
/// This allows the `Phase` to be generic over either `ConstHz` and `Hz<I>`.
///
/// Generally, users need not be concerned with this trait unless writing code that must remain
/// generic over phase stepping types like oscillators.
pub trait Step {
    /// Yield the phase step size (normally `hz / sampling rate`).
    ///
    /// The `Phase` calls this and uses the returned value to step forward its internal `phase`.
    fn step(&mut self) -> f64;
}

impl Step for ConstHz {
    #[inline]
    fn step(&mut self) -> f64 {
        self.step
    }
}

impl<I> Step for Hz<I>
    where I: Iterator<Item=f64>,
{
    #[inline]
    fn step(&mut self) -> f64 {
        match self.hz.next() {
            Some(hz) => {
                self.last_step_size = hz / self.rate.hz;
                hz
            },
            None => self.last_step_size,
        }
    }
}


impl<S> Phase<S>
    where S: Step,
{

    /// Before yielding the current phase, the internal phase is stepped forward and wrapped via
    /// the given value.
    #[inline]
    pub fn next_phase_wrapped_to(&mut self, rem: f64) -> f64 {
        let phase = self.next;
        self.next = (self.next + self.step.step()) % rem;
        phase
    }

    /// Calls `next_phase_wrapped_to`, with a wrapping value of `1.0`.
    #[inline]
    pub fn next_phase(&mut self) -> f64 {
        self.next_phase_wrapped_to(1.0)
    }

    /// A composable version of the `signal::sine` function.
    #[inline]
    pub fn sine(self) -> Sine<S> {
        sine(self)
    }

    /// A composable version of the `signal::saw` function.
    #[inline]
    pub fn saw(self) -> Saw<S> {
        saw(self)
    }

    /// A composable version of the `signal::square` function.
    #[inline]
    pub fn square(self) -> Square<S> {
        square(self)
    }

    /// A composable version of the `signal::noise_simplex` function.
    #[inline]
    pub fn noise_simplex(self) -> NoiseSimplex<S> {
        noise_simplex(self)
    }

}


impl<I> Iterator for Hz<I>
    where I: Iterator<Item=f64>,
{
    type Item = f64;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.step())
    }
}


impl Iterator for ConstHz {
    type Item = f64;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some(self.step())
    }
}


impl<S> Iterator for Phase<S>
    where S: Step,
{
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some([self.next_phase()])
    }
}


impl<S> Iterator for Sine<S>
    where S: Step,
{
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        const PI_2: f64 = core::f64::consts::PI * 2.0;
        let phase = self.phase.next_phase();
        Some([::sin(PI_2 * phase)])
    }
}


impl<S> Iterator for Saw<S>
    where S: Step,
{
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let phase = self.phase.next_phase();
        Some([phase * -2.0 + 1.0])
    }
}


impl<S> Iterator for Square<S>
    where S: Step,
{
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        let phase = self.phase.next_phase();
        Some([if phase < 0.5 { 1.0 } else { -1.0 }])
    }
}


impl Noise {
    #[inline]
    pub fn next_sample(&mut self) -> f64 {
        // A simple one-dimensional noise generator.
        //
        // Credit for the pseudo code from which this was translated goes to Hugo Elias and his
        // excellent primer on perlin noise at
        // http://freespace.virgin.net/hugo.elias/models/m_perlin.htm
        fn noise_1(seed: u64) -> f64 {
            const PRIME_1: u64 = 15_731;
            const PRIME_2: u64 = 789_221;
            const PRIME_3: u64 = 1_376_312_589;
            let x = (seed << 13) ^ seed;
            1.0 - (
                x.wrapping_mul(x.wrapping_mul(x).wrapping_mul(PRIME_1).wrapping_add(PRIME_2))
                    .wrapping_add(PRIME_3) & 0x7fffffff
            ) as f64 / 1_073_741_824.0
        }

        let noise = noise_1(self.seed);
        self.seed += 1;
        noise
    }
}

impl Iterator for Noise {
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some([self.next_sample()])
    }
}


impl<S> NoiseSimplex<S>
    where S: Step,
{
    #[inline]
    pub fn next_sample(&mut self) -> f64 {
        // The constant remainder used to wrap the phase back to 0.0.
        //
        // This is the first power of two that is over double the human hearing range. This should
        // allow for simplex noise to be generated at a frequency matching the extent of the human
        // hearing range while never repeating more than once per second; the repetition would
        // likely be indistinguishable at such a high frequency, and in this should be practical
        // for audio simplex noise.
        const TWO_POW_SIXTEEN: f64 = 65_536.0;
        let phase = self.phase.next_phase_wrapped_to(TWO_POW_SIXTEEN);

        // 1D Perlin simplex noise.
        //
        // Takes a floating point x coordinate and yields a noise value in the range of -1..1, with
        // value of 0.0 on all integer coordinates.
        //
        // This function and the enclosing functions have been adapted from SRombauts' MIT licensed
        // C++ implementation at the following link: https://github.com/SRombauts/SimplexNoise
        fn simplex_noise_1d(x: f64) -> f64 {

            // Permutation table. This is a random jumble of all numbers 0...255.
            const PERM: [u8; 256] = [
                151, 160, 137, 91, 90, 15, 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36,
                103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, 190, 6, 148, 247, 120, 234, 75, 0,
                26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, 88, 237, 149, 56, 87,
                174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, 77, 146,
                158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40,
                244, 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18,
                169, 200, 196, 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64,
                52, 217, 226, 250, 124, 123, 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206,
                59, 227, 47, 16, 58, 17, 182, 189, 28, 42, 223, 183, 170, 213, 119, 248, 152, 2,
                44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, 129, 22, 39, 253, 19, 98,
                108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, 251, 34, 242,
                193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107,
                49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4,
                150, 254, 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66,
                215, 61, 156, 180
            ];

            // Hashes the given integer with the above permutation table.
            fn hash(i: i64) -> u8 {
                PERM[(i as u8) as usize]
            }

            // Computes the gradients-dot-residual vectors (1D).
            fn grad(hash: i64, x: f64) -> f64 {
                // Convert low 4 bits of hash code.
                let h = hash & 0x0F;
                // Gradien value 1.0, 2.0, ..., 8.0.
                let mut grad = 1.0 + (h & 7) as f64;
                // Set a random sign for the gradient.
                if (h & 8) != 0 { grad = -grad; }
                // Multiply the gradient with the distance.
                grad * x
            }

            // Corners coordinates (nearest integer values).
            let i0 = ::floor(x) as i64;
            let i1 = i0 + 1;

            // Distances to corners (between 0 and 1);
            let x0 = x - i0 as f64;
            let x1 = x0 - 1.0;

            // Calculate the contribution from the first corner.
            let mut t0 = 1.0 - x0 * x0;
            t0 *= t0;
            let n0 = t0 * t0 * grad(hash(i0) as i64, x0);

            // Calculate the contribution rom the second corner.
            let mut t1 = 1.0 - x1 * x1;
            t1 *= t1;
            let n1 = t1 * t1 * grad(hash(i1) as i64, x1);

            // The max value of this noise is 2.53125. 0.395 scales to fit exactly within -1..1.
            0.395 * (n0 + n1)
        }

        simplex_noise_1d(phase)
    }
}

impl<S> Iterator for NoiseSimplex<S>
    where S: Step,
{
    type Item = [f64; 1];
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        Some([self.next_sample()])
    }
}


#[inline]
fn zipped_size_hint<A, B>(a: &A, b: &B) -> (usize, Option<usize>)
    where A: Iterator,
          B: Iterator,
{
    let (a_lower, a_upper) = a.size_hint();
    let (b_lower, b_upper) = b.size_hint();
    let lower = core::cmp::min(a_lower, b_lower);
    let upper = match (a_upper, b_upper) {
        (Some(a), Some(b)) => Some(core::cmp::min(a, b)),
        (Some(a), None) => Some(a),
        (None, Some(b)) => Some(b),
        (None, None) => None,
    };
    (lower, upper)
}


impl<A, B> Iterator for AddAmp<A, B>
    where A: Signal,
          B: Signal,
          A::Item: Frame,
          B::Item: Frame<Sample=<<A::Item as Frame>::Sample as Sample>::Signed,
                         NumChannels=<A::Item as Frame>::NumChannels>,
{
    type Item = A::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.a.next().and_then(|a_f| self.b.next().map(|b_f| a_f.add_amp(b_f)))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        zipped_size_hint(&self.a, &self.b)
    }
}

impl<A, B> ExactSizeIterator for AddAmp<A, B>
    where AddAmp<A, B>: Iterator,
          A: ExactSizeIterator,
          B: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        core::cmp::min(self.a.len(), self.b.len())
    }
}


impl<A, B> Iterator for MulAmp<A, B>
    where A: Signal,
          B: Signal,
          A::Item: Frame,
          B::Item: Frame<Sample=<<A::Item as Frame>::Sample as Sample>::Float,
                         NumChannels=<A::Item as Frame>::NumChannels>,
{
    type Item = A::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.a.next().and_then(|a_f| self.b.next().map(|b_f| a_f.mul_amp(b_f)))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        zipped_size_hint(&self.a, &self.b)
    }
}

impl<A, B> ExactSizeIterator for MulAmp<A, B>
    where MulAmp<A, B>: Iterator,
          A: ExactSizeIterator,
          B: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        core::cmp::min(self.a.len(), self.b.len())
    }
}


impl<S> Iterator for ScaleAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.signal.next().map(|f| f.scale_amp(self.amp))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.signal.size_hint()
    }
}

impl<S> ExactSizeIterator for ScaleAmp<S>
    where S: Signal + ExactSizeIterator,
          S::Item: Frame,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len()
    }
}


impl<S, F> Iterator for ScaleAmpPerChannel<S, F>
    where S: Signal,
          S::Item: Frame,
          F: Frame<Sample=<<S::Item as Frame>::Sample as Sample>::Float,
                   NumChannels=<S::Item as Frame>::NumChannels>,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.signal.next().map(|f| f.mul_amp(self.amp_frame))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.signal.size_hint()
    }
}

impl<S, F> ExactSizeIterator for ScaleAmpPerChannel<S, F>
    where ScaleAmpPerChannel<S, F>: Iterator,
          S: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len()
    }
}


impl<S> Iterator for OffsetAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.signal.next().map(|f| f.offset_amp(self.offset))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.signal.size_hint()
    }
}

impl<S> ExactSizeIterator for OffsetAmp<S>
    where S: Signal + ExactSizeIterator,
          S::Item: Frame,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len()
    }
}


impl<S, F> Iterator for OffsetAmpPerChannel<S, F>
    where S: Signal,
          S::Item: Frame,
          F: Frame<Sample=<<S::Item as Frame>::Sample as Sample>::Signed,
                   NumChannels=<S::Item as Frame>::NumChannels>,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.signal.next().map(|f| f.add_amp(self.amp_frame))
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        self.signal.size_hint()
    }
}

impl<S, F> ExactSizeIterator for OffsetAmpPerChannel<S, F>
    where OffsetAmpPerChannel<S, F>: Iterator,
          S: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len()
    }
}


impl<S, M> Iterator for MulHz<S, M>
    where S: Signal,
          S::Item: Frame,
          <S::Item as Frame>::Sample: Duplex<f64>,
          M: Iterator<Item=f64>,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.mul_per_frame.next().and_then(|mul| {
            self.signal.set_playback_hz_scale(mul);
            self.signal.next()
        })
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        // We can't make any guarantees about size here as the rate may change dramatically at any
        // point.
        (1, None)
    }
}


impl<S> Iterator for Delay<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.n_frames > 0 {
            self.n_frames -= 1;
            Some(Frame::equilibrium())
        } else {
            self.signal.next()
        }
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (lower, upper) = self.signal.size_hint();
        (lower + self.n_frames, upper.map(|n| n + self.n_frames))
    }
}

impl<S> ExactSizeIterator for Delay<S>
    where Delay<S>: Iterator,
          S: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len() + self.n_frames
    }
}


impl<S> Iterator for ToSamples<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = <S::Item as Frame>::Sample;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        loop {
            if let Some(ref mut frame) = self.current_frame {
                if let Some(channel) = frame.next() {
                    return Some(channel);
                }
            }
            self.current_frame = match self.signal.next() {
                Some(frame) => Some(frame.channels()),
                None => return None,
            };
        }
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let (lower, upper) = self.signal.size_hint();
        let current_frame = self.current_frame.as_ref().map(|chans| chans.size_hint());
        let n_channels = <S::Item as Frame>::n_channels();
        let lower = lower * n_channels + current_frame.map(|sh| sh.0).unwrap_or(0);
        let upper = upper.and_then(|upper| {
            let current_upper = match current_frame.map(|sh| sh.1) {
                None => 0,
                Some(None) => return None,
                Some(Some(n)) => n,
            };
            Some(upper * n_channels + current_upper)
        });
        (lower, upper)
    }
}

impl<S> Clone for ToSamples<S>
    where S: Signal + Clone,
          S::Item: Frame,
          <S::Item as Frame>::Channels: Clone,
{
    #[inline]
    fn clone(&self) -> Self {
        ToSamples {
            signal: self.signal.clone(),
            current_frame: self.current_frame.clone(),
        }
    }
}

impl<S> ExactSizeIterator for ToSamples<S>
    where ToSamples<S>: Iterator,
          S: ExactSizeIterator,
          S::Item: Frame,
          <S::Item as Frame>::Channels: ExactSizeIterator,
{
    #[inline]
    fn len(&self) -> usize {
        self.signal.len() * <S::Item as Frame>::n_channels()
            + self.current_frame.as_ref().map(|f| f.len()).unwrap_or(0)
    }
}


impl<S> Iterator for ClipAmp<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.signal.next().map(|f| f.map(|s| {
            let s: <<S::Item as Frame>::Sample as Sample>::Signed = s.to_sample();
            if s > self.thresh { self.thresh } else if s < -self.thresh { -self.thresh } else { s }
                .to_sample()
        }))
    }
}


impl<S> Bus<S>
    where S: Signal,
          S::Item: Frame,
{
    /// Produce a new Output node to which the signal `S` will output its frames.
    #[inline]
    pub fn send(&self) -> Output<S> {
        let idx = self.node.borrow().buffers.len();
        self.node.borrow_mut().buffers.push(VecDeque::new());
        Output {
            idx: idx,
            node: self.node.clone(),
        }
    }
}

impl<S> SharedNode<S>
    where S: Signal,
          S::Item: Frame,
{

    /// Requests the next frame for the `Output` whose ring buffer lies at the given index.
    ///
    /// If there are no frames waiting in the front of the ring buffer, a new frame will be
    /// requested from the `signal` and appended to the back of each ring buffer.
    #[inline]
    fn next_frame(&mut self, idx: usize) -> Option<S::Item> {
        loop {
            match self.buffers[idx].pop_front() {
                Some(frame) => return Some(frame),
                None => match self.signal.next() {
                    Some(frame) => {
                        for buffer in self.buffers.iter_mut() {
                            buffer.push_back(frame);
                        }
                    },
                    None => return None,
                }
            }
        }
    }

    #[inline]
    fn pending_frames(&self, idx: usize) -> usize {
        self.buffers[idx].len()
    }

}

impl<S> Output<S>
    where S: Signal,
          S::Item: Frame,
{
    /// The number of frames that have been requested from the `Signal` `S` by some other `Output`
    /// that have not yet been requested by this `Output`.
    ///
    /// This is useful when using an `Output` to "monitor" some signal, allowing the user to drain
    /// only frames that have already been requested by some other `Output`.
    ///
    /// # Example
    ///
    /// ```rust
    /// extern crate sample;
    ///
    /// use sample::Signal;
    ///
    /// fn main() {
    ///     let frames = [[0.1], [0.2], [0.3]];
    ///     let bus = frames.iter().cloned().bus();
    ///     let mut signal = bus.send();
    ///     let mut monitor = bus.send();
    ///     assert_eq!(signal.collect::<Vec<_>>(), vec![[0.1], [0.2], [0.3]]);
    ///     assert_eq!(monitor.pending_frames(), 3);
    ///     assert_eq!(monitor.next(), Some([0.1]));
    ///     assert_eq!(monitor.pending_frames(), 2);
    /// }
    /// ```
    #[inline]
    pub fn pending_frames(&self) -> usize {
        self.node.borrow().pending_frames(self.idx)
    }
}

impl<S> Iterator for Output<S>
    where S: Signal,
          S::Item: Frame,
{
    type Item = S::Item;
    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        self.node.borrow_mut().next_frame(self.idx)
    }
    #[inline]
    fn size_hint(&self) -> (usize, Option<usize>) {
        let node = self.node.borrow();
        let (lower, upper) = node.signal.size_hint();
        let n = node.buffers[self.idx].len();
        (lower + n, upper.map(|upper| upper + n))
    }
}