package tiny_libs

  1. Overview
  2. Docs
From-scratch libraries for teaching: graphics, audio, compression, crypto, networking and more

Install

dune-project
 Dependency

Authors

Maintainers

Sources

0.3.6.tar.gz
md5=7c636383d146d30ac6f2fa234a6253c8
sha512=c79f3823c5f8f57e5038eb640d487c61168b84aa07c61999d6622ef9fd0c890e2b03b4c6a7cdbbe9352a49e25dda00ac7bb14693cee8e3d7beeed251351a2af0

doc/src/tiny_libs.audio_instruments/Lfo.ml.html

Source file Lfo.ml

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
(* Claude Code
 *
 * Copyright (C) 2026 Yoann Padioleau
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public License
 * (LGPL) as published by the Free Software Foundation; either version
 * 2 of the License, or (at your option) any later version.
 *)

(* See Lfo.mli *)

type shape = Sine | Triangle | Square | Saw_up | Saw_down | Sample_and_hold

let shapes = [ Sine; Triangle; Square; Saw_up; Saw_down; Sample_and_hold ]

let name = function
  | Sine -> "sine"
  | Triangle -> "triangle"
  | Square -> "square"
  | Saw_up -> "saw up"
  | Saw_down -> "saw down"
  | Sample_and_hold -> "sample & hold"

let value (shape : shape) (phase : float) : float =
  match shape with
  | Sine -> Oscillator.wave Sine phase
  | Triangle -> Oscillator.wave Triangle phase
  | Square -> Oscillator.wave Square phase
  | Saw_up -> Oscillator.wave Sawtooth phase
  | Saw_down -> -.Oscillator.wave Sawtooth phase
  | Sample_and_hold -> 0.

(* the phase; the random generator's state, and the value it last drew,
 * held *)
type t = { mutable phase : float; mutable random : int; mutable held : float }

let create ?(seed = 0) () : t =
  let random = Noise.lcg seed in
  { phase = 0.; random; held = Noise.uniform random }

let fill (t : t) (shape : shape) ~(rate : float) (out : Signal.t) : unit =
  let dphase = rate /. float_of_int Signal.rate in
  for i = 0 to Array.length out - 1 do
    out.(i) <- (match shape with Sample_and_hold -> t.held | _ -> value shape t.phase);
    let next = t.phase +. dphase in
    (* a new period: sample and hold draws its next value *)
    if next >= 1. then (
      t.random <- Noise.lcg t.random;
      t.held <- Noise.uniform t.random);
    t.phase <- next -. Float.floor next
  done

let unipolar (x : float) : float = (x +. 1.) /. 2.
let of_tempo ~(bpm : float) ~(beats : float) : float = bpm /. 60. /. beats