Metadata-Version: 2.4
Name: chiptune
Version: 0.1.0
Summary: Professional audio engine and music creation toolkit
Author-email: Bs64Sha256 <bs64sha256@gmail.com>
License-Expression: MIT
Project-URL: Homepage, https://github.com/bs64sha256/chiptune
Project-URL: Repository, https://github.com/bs64sha256/chiptune
Keywords: audio,synthesizer,music,sound-design,midi
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Education
Classifier: Topic :: Multimedia :: Sound/Audio
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Operating System :: OS Independent
Requires-Python: >=3.9
Description-Content-Type: text/markdown
License-File: LICENSE
Provides-Extra: numpy
Requires-Dist: numpy>=1.20; extra == "numpy"
Provides-Extra: full
Requires-Dist: numpy>=1.20; extra == "full"
Requires-Dist: sounddevice>=0.4; extra == "full"
Dynamic: license-file

# 🎵 Chiptune — Professional Audio Engine for Python

A full‑featured modular system for music creation, sound design, and audio processing.  
Combines synthesis, sequencing, effects, automation, import/export, and optimisation — all in pure Python.

---

## 📦 Installation

Install from PyPI:
```bash
pip install chiptune
```

For optional acceleration and streaming support:
```bash
pip install "chiptune[numpy]"          # numpy‑accelerated waveforms & convolution
pip install "chiptune[full]"           # numpy + sounddevice for real‑time playback
```

---

## 🏗 Architecture
```
chiptune/
    sound.py            # Waveform generator (sine, square, saw, triangle)
    track.py            # Track (notes, rests, effects, automation)
    composition.py      # Composition (track collection, BPM)
    instruments.py      # Instruments and Note class
    effects.py          # Reverb, delay, distortion, etc.
    sfx.py              # Sound effects library (55+)
    tempo.py            # Musical durations and BPM
    automation.py       # Envelopes and LFOs
    music.py            # Patterns, chords, articulations
    fm_synth.py         # FM synthesis
    subtractive_synth.py# Subtractive synthesis
    granular.py         # Granular synthesis
    sampler.py          # Sampler (WAV import)
    eq.py               # Equalizers
    filters.py          # Dynamic filters with automation
    limiter.py          # Limiter
    convolver.py        # Convolution reverb
    presets.py          # Ready‑to‑use instruments and drum kits
    renderer.py         # WAV / MIDI export
    midi_writer.py      # MIDI writer
    midi_reader.py      # MIDI reader
    player.py           # Preview playback
    streaming.py        # Streaming playback
    optimization.py     # Caching, NumPy, parallel rendering
    utils.py            # Helpers (note parsing, MIDI conversion, clipping)
```

---

## 🚀 Quick Start
```python
from chiptune import *

piano = Piano()
note  = Note(piano, parse_note('C5'), Quarter(), 0.7)
track = Track(items=[note, Rest(Eighth()), note])
comp  = Composition(tracks=[track], bpm=120)

save_wav(comp, 'hello.wav')
preview(comp)
```

---

## 🧱 Core Concepts

### 🎚 Sound – Waveform Generator
```python
Sound(frequency=440.0, duration=1.0, amplitude=1.0, waveform='sine', pan=0.0)
```
- `waveform`: `'sine'`, `'square'`, `'sawtooth'`, `'triangle'`
- `pan`: from -1 (left) to 1 (right)
- `generate(sample_rate)` returns a list of float samples.

### ⏱ Rest – Silence
```python
Rest(duration=0.5)               # seconds
Rest(Quarter())                  # musical duration (BPM‑aware)
```

### 🎼 MusicalDuration – Note Lengths
- `Whole()` – whole note
- `Half()` – half note
- `Quarter()` – quarter note
- `Eighth()` – eighth note
- `Sixteenth()` – sixteenth note
- `Thirtysecond()` – thirty‑second note
- `dotted(d)` – 1.5× duration
- `triplet(d)` – 2/3 of a beat

Addition and multiplication:
```python
d = Quarter() + Eighth()   # dotted quarter
d = 2 * Quarter()          # half note
```

### 🎵 Track
```python
Track(items=[...], volume=1.0, effects=[...], loop_count=1,
      volume_envelope=None, pan_envelope=None, filter_envelope=None,
      lfo_volume=None, lfo_pan=None)
```
Methods:
- `add(item)` – add an element
- `render(sample_rate, bpm)` – generate stereo buffers (left, right)
- `duration(bpm)` – length in seconds
- `transpose(semitones)` – transpose all notes

**Automation**:
- `volume_envelope` – `Envelope` instance for volume modulation over time
- `pan_envelope` – pan envelope
- `filter_envelope` – filter cutoff envelope (requires a `Filter` effect)
- `lfo_volume` / `lfo_pan` – LFO for volume/pan modulation

### 🎶 Composition
```python
Composition(tracks=[...], volume=1.0, master_effects=[...], bpm=120)
```
Methods:
- `render(sample_rate, parallel=False)` – render the whole composition
- `duration()` – total length in seconds

---

## 🎹 Instruments

### Built‑in Classes
| Instrument | Constructor parameters |
|------------|------------------------|
| `AcousticGuitar` | `decay`, `brightness`, `harmonic_count` |
| `ElectricGuitar` | `gain`, `distortion`, `decay`, `brightness`, `harmonic_count` |
| `Piano` | `decay`, `inharmonicity`, `brightness`, `harmonic_count` |
| `Trumpet` | `attack`, `decay`, `sustain_level`, `release`, `vibrato_rate`, `vibrato_depth`, `brightness` |
| `Kick` | `freq_start`, `freq_end`, `decay` |
| `Snare` | `tone_freq`, `tone_decay`, `noise_decay`, `noise_level` |
| `Hihat` | `decay` |

### Universal Note – `Note`
```python
Note(instrument, frequency, duration, amplitude=1.0, pan=0.0,
     attack=None, decay=None, sustain=None, release=None)
```
- `frequency` – number or result of `parse_note('C#4')`
- `duration` – float or `MusicalDuration`
- ADSR parameters override the amplitude envelope of the note.

### Per‑Note ADSR Envelope
```python
Note(piano, 440, Quarter(), attack=0.2, decay=0.1, sustain=0.8, release=0.3)
```

### Note Caching
Identical notes with the same instrument, frequency, duration, and amplitude are cached – repeated fragments render instantly.

---

## 🎛 Advanced Synthesis

### FM Synthesis (`FMSynth`)
```python
fm = FMSynth(algorithm='simple')  # or pass a list of operator dicts
```
Each operator: `{'ratio': 1.0, 'amplitude': 1.0, 'envelope': {...}}`  
Generate: `fm.generate(freq, duration, amp, sample_rate)`

### Subtractive Synthesis (`SubtractiveSynth`)
```python
sub = SubtractiveSynth(waveform='sawtooth', cutoff=2000, resonance=0.2,
                       filter_type='lp', lfo_rate=0.5, lfo_depth=0.3,
                       envelope=ADSREnvelope(0.01, 0.1, 0.8, 0.3))
```

### Granular Synthesis (`GranularSynth`)
```python
grain = Grain(audio_data, position=0.2, length=0.3, amplitude=0.8)
granular = GranularSynth(grains=[grain1, grain2], overlap=0.5)
samples = granular.generate(duration, sample_rate)
```

### Sampler (`Sampler`)
```python
sampler = Sampler('sound.wav')
samples = sampler.generate(frequency=440, duration=2.0, amplitude=0.8, sample_rate=44100)
```
Supports pitch‑shifting (playback speed adjustment).

---

## 🎚 Audio Processing (Effects)

All effects implement `apply(samples, sample_rate)` and can be used in a track’s effect chain or on the master bus.

### 🏠 Reverb & Delay
- **Reverb** `(room_size, damping, wet_level, dry_level, width)`
- **Delay** `(delay_time, feedback, wet_level, dry_level)`

### 🌊 Modulation Effects
- **Chorus** `(rate, depth, mix, voices)`
- **Flanger** `(rate, depth, feedback, mix)`
- **Phaser** `(rate, depth, feedback, stages, mix)`

### 🔥 Distortions
- **Saturation** `(drive, mix)`
- **Distortion** `(gain, tone)`
- **Overdrive** `(drive, tone, mix)`
- **Bitcrusher** `(bits, rate)`

### 📈 Dynamics
- **Compressor** `(threshold, ratio, attack, release, makeup_gain)`
- **Limiter** `(threshold, release, ceiling)`

### 🎛 Equalizers
- **ParametricEQ** `(bands=[(freq, gain_db, Q), ...])`
- **GraphicEQ** `(gains={200: 4.0, 4000: -3.0})`

### 🎚 Filter with Automation (`Filter`)
```python
filt = Filter(filter_type='lp', cutoff=1000, resonance=0.5, envelope=my_envelope)
```
Types: `'lp'`, `'hp'`, `'bp'`, `'notch'`.

### 🏰 Convolution Reverb (`ConvolutionReverb`)
```python
conv = ConvolutionReverb('hall_ir.wav', mix=0.6)
```
If `numpy` is available, FFT convolution is used for a massive speedup.

---

## 📈 Automation & Modulation

### Envelope
```python
env = Envelope([(0.0, 0.0), (0.2, 1.0), (1.5, 1.0), (2.0, 0.0)])
```
Static factory: `Envelope.from_adsr(attack, decay, sustain, release, total_duration)`.

### ADSREnvelope
```python
adsr = ADSREnvelope(attack=0.1, decay=0.2, sustain=0.7, release=0.4)
```

### LFO – Low‑Frequency Oscillator
```python
lfo = LFO(rate=2.0, depth=0.5, waveform='sine', phase=0.0)
```
Waveforms: `'sine'`, `'square'`, `'triangle'`, `'sawtooth'`.

**Applied to a track**:
```python
track = Track(items=[...], volume_envelope=env, lfo_pan=lfo, pan_envelope=...)
```

---

## 🥁 Presets & Drum Kits

### Ready‑made Instruments
- `Violin()`
- `BassGuitar()`
- `Organ()`
- `SynthLead()`
- `SynthPad()`

### Effect Presets
- `reverb_room()` – small room
- `reverb_hall()` – large hall
- `echo_standard()` – echo
- `distortion_metal()` – heavy distortion
- `overdrive_boost()` – overdrive
- `compressor_master()` – mastering compressor

### Drum Kits
```python
drum_kit = DrumKit()
drums_track = drum_kit.get_track(style='rock', bpm=120)
```
Styles: `'basic'`, `'rock'`.

---

## 🎶 Sequencer & Musical Constructions

### Pattern
```python
pattern = Pattern(items=[note1, note2], beats=4, repeat=2)
```
Method `flatten()` expands all repetitions.

### Chord
```python
chord = Chord("Cmaj7", Half(), piano, amplitude=0.6)
```
Supported suffixes: `major`, `minor`, `dim`, `aug`, `maj7`, `min7`, `7`, `dim7`, `m7b5`.  
Generates a list of `Note` objects and mixes them into a single buffer.

### Articulations
- **Staccato** `(note, factor=0.5)` – shortens a note
- **Legato** `([note1, note2, ...])` – merges notes into a continuous sound
- **Trill** `(note1, note2, speed=0.1, duration=None)` – rapid alternation between two notes

---

## 🔊 SFX – Sound Effects Library
Over **55** high‑quality synthesised sounds.  
Usage:
```python
sfx = SFXSound('explosion', amplitude=0.9, pan=0.2)
track = Track(items=[sfx])
```

Full list:
`explosion`, `laser`, `button_click`, `jump`, `coin`, `hit`, `zap`, `swoosh`, `thunder`, `rain`, `footsteps`, `gunshot`, `teleport`, `sparkle`, `magic`, `sword_clash`, `glass_break`, `bubble_pop`, `electricity`, `alarm`, `siren`, `heartbeat`, `water_drop`, `fire_crackle`, `wind`, `robot_voice`, `pickup`, `drop`, `splash`, `whoosh`, `rumble`, `click`, `beep`, `buzz`, `chirp`, `applause`, `laugh`, `scream`, `ricochet`, `reload`, `grenade`, `rocket_launch`, `countdown`, `tick`, `clock`, `bell`, `chime`, `harp`, `triangle`, `modem`, `glitch`, `engine_start`, `engine_loop`, `camera_shutter`, `typewriter`, `ping`.

---

## 💾 Import / Export

### Save WAV
```python
save_wav(composition, 'output.wav', sample_rate=44100, bit_depth=16)
```

### Save MIDI
```python
save_midi(composition, 'output.mid', ticks_per_beat=480, tempo=120)
```
Instrument parameters are stored in text meta‑events.

### Read MIDI
```python
comp = import_midi('input.mid')
```
Automatically restores `Note` objects with original instruments, amplitude, and panning; inserts rests.

---

## ⚡ Performance

### Note Caching
Each unique combination (instrument, frequency, duration, amplitude, sample_rate) is generated only once.

### NumPy (optional)
Dramatically accelerates waveform generation and convolution. Install `numpy` to enable automatically.

### Parallel Rendering
```python
left, right = comp.render(parallel=True)
```
Distributes track rendering across CPU cores.

---

## 🎧 Streaming Playback
```python
def my_callback(composition):
    composition.tracks[0].volume = 0.5   # modify on the fly

player = StreamingPlayer(composition, callback=my_callback, block=False)
player.start()
```
(Feature under development – callback is called between chunks.)

---

## 🛠 Utilities

### Note Parsing
```python
parse_note('C#4')  # 277.1826309768721
```

### MIDI ↔ Frequency Conversion
```python
frequency_to_midi_note(440)   # 69
midi_note_to_frequency(69)    # 440.0
```

### Instrument Factory
```python
piano = create_instrument('Piano', {'decay': 2.0})
```

---

## 🎓 Creating Custom Instruments & Effects
Inherit from `Instrument` and implement `generate(frequency, duration, amplitude, sample_rate)`.  
For effects, implement `apply(samples, sample_rate)`.

Example:
```python
class MySynth(Instrument):
    def generate(self, freq, dur, amp, sr):
        n = int(dur * sr)
        return [math.sin(2*math.pi*freq*i/sr)*amp for i in range(n)]
```

---

## ❓ FAQ

**Q: No sound during preview?**  
A: Check that note amplitude > 0, duration > 0, and track/composition volume > 0.

**Q: MIDI import loses instruments?**  
A: Only MIDIs created by this engine are fully restored. External MIDIs are imported as `Sound` with a sine wave.

**Q: Rendering is too slow?**  
A: Install `numpy`, use `parallel=True` when rendering; caching is always active.

---

## 📄 License
MIT – do whatever you want. Attribution appreciated.

---

> Built with love for music and code 🎵  
> Full list of features and classes is available in the source code.
