├── circle_dance ├── __init__.py ├── audio │ ├── read │ │ ├── file.py │ │ ├── __init__.py │ │ ├── callbacks.py │ │ └── stream.py │ ├── __init__.py │ ├── split │ │ └── __init__.py │ └── process │ │ ├── __init__.py │ │ ├── note_onsets.py │ │ └── note_durations.py ├── cli │ ├── __init__.py │ ├── subcommands │ │ ├── __init__.py │ │ ├── base.py │ │ ├── listen.py │ │ └── play.py │ └── entrypoint.py ├── game │ ├── __init__.py │ ├── modules │ │ ├── __init__.py │ │ ├── music_player.py │ │ ├── base.py │ │ ├── circular_sheet_file.py │ │ └── circular_sheet_stream.py │ └── game.py ├── visualize │ ├── __init__.py │ ├── types.py │ ├── circular_sheet │ │ ├── utils.py │ │ ├── config.py │ │ ├── __init__.py │ │ ├── pointer.py │ │ ├── sheet.py │ │ ├── canvas.py │ │ ├── note_pool.py │ │ └── notes.py │ ├── drawable.py │ └── draw.py └── config.py ├── research └── .gitignore ├── screenshot.png ├── README.md ├── pyproject.toml ├── .pre-commit-config.yaml ├── TODO.md ├── .gitignore ├── DEVELOPMENT.md └── LICENSE /circle_dance/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /research/.gitignore: -------------------------------------------------------------------------------- 1 | audio/ 2 | -------------------------------------------------------------------------------- /circle_dance/audio/read/file.py: -------------------------------------------------------------------------------- 1 | # file reader 2 | -------------------------------------------------------------------------------- /circle_dance/audio/__init__.py: -------------------------------------------------------------------------------- 1 | # audio data handling 2 | -------------------------------------------------------------------------------- /screenshot.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/loli/circle_dance/main/screenshot.png -------------------------------------------------------------------------------- /circle_dance/cli/__init__.py: -------------------------------------------------------------------------------- 1 | # command line interface, main entrypoint and subcommands 2 | -------------------------------------------------------------------------------- /circle_dance/game/__init__.py: -------------------------------------------------------------------------------- 1 | # game aka visualization runner 2 | from circle_dance.game.game import Game 3 | 4 | __all__ = ["Game"] 5 | -------------------------------------------------------------------------------- /circle_dance/visualize/__init__.py: -------------------------------------------------------------------------------- 1 | # visualizations 2 | 3 | from circle_dance.visualize.drawable import Drawable 4 | 5 | __all__ = ["Drawable"] 6 | -------------------------------------------------------------------------------- /circle_dance/audio/split/__init__.py: -------------------------------------------------------------------------------- 1 | # audio data splitters 2 | # functionality to split audio data into various elements, e.g. by stem or frequency range 3 | -------------------------------------------------------------------------------- /circle_dance/visualize/types.py: -------------------------------------------------------------------------------- 1 | # common types 2 | 3 | from typing import TypeAlias 4 | 5 | T_COLOR: TypeAlias = tuple[int, int, int] | tuple[int, int, int, int] 6 | -------------------------------------------------------------------------------- /circle_dance/audio/read/__init__.py: -------------------------------------------------------------------------------- 1 | # audio data readers 2 | # functionality to read audio data from various sources, like files or sound sources 3 | 4 | from circle_dance.audio.read.stream import stream_reader 5 | 6 | __all__ = ["stream_reader"] 7 | -------------------------------------------------------------------------------- /circle_dance/config.py: -------------------------------------------------------------------------------- 1 | # global config 2 | 3 | note_ids_to_names = { 4 | 0: "C", 5 | 1: "C#", 6 | 2: "D", 7 | 3: "D#", 8 | 4: "E", 9 | 5: "F", 10 | 6: "F#", 11 | 7: "G", 12 | 8: "G#", 13 | 9: "A", 14 | 10: "A#", 15 | 11: "B", 16 | } 17 | -------------------------------------------------------------------------------- /circle_dance/audio/process/__init__.py: -------------------------------------------------------------------------------- 1 | # audio data processing 2 | # functionality to extract notes and note attributes form audio data 3 | 4 | from circle_dance.audio.process.note_durations import extract_note_durations 5 | from circle_dance.audio.process.note_onsets import extract_note_onsets 6 | 7 | __all__ = ["extract_note_onsets", "extract_note_durations"] 8 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/utils.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: utility functions 2 | 3 | import math 4 | 5 | from circle_dance.visualize.circular_sheet import config 6 | 7 | 8 | def get_angle_at_time(t: float) -> float: 9 | """Get the rotation angle in radians at a certain time in second.""" 10 | return (t % config.rotation_period) * (2 * math.pi / config.rotation_period) 11 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Circle Dance 2 | 3 | Visualization library and tool for music streams. Can either play and visualize a song or read from a sound device as steam input. 4 | 5 | ## Installation 6 | `poetry install` 7 | 8 | ## Usage 9 | - To play: `circle_dance play songs/song.mp3 --note-type=dot -t 0.75` 10 | - To listen: `circle_dance play listen --note-type=sarc -t 0.9` 11 | 12 | ## Screenshot 13 | ![screenshot](screenshot.png) 14 | -------------------------------------------------------------------------------- /circle_dance/visualize/drawable.py: -------------------------------------------------------------------------------- 1 | # base class for all drawable objects 2 | 3 | from abc import ABC, abstractmethod 4 | 5 | import pygame 6 | 7 | 8 | class Drawable(ABC): 9 | 10 | def __init__(self, surface: pygame.Surface): 11 | """A drawable. 12 | 13 | Args: 14 | surface: the surface this drawable draws itself on 15 | """ 16 | self.surface = surface 17 | 18 | @abstractmethod 19 | def draw(self, t: float) -> None: 20 | pass 21 | -------------------------------------------------------------------------------- /circle_dance/cli/subcommands/__init__.py: -------------------------------------------------------------------------------- 1 | # CLI subcommands 2 | # All subcommands are scripts in their own right, but usually only accessed through the main entrypoint 3 | # A subcommand mostly defines a game via the base game in connection with a selection of game modules 4 | 5 | from circle_dance.cli.subcommands.base import BaseSubcommand, classproperty 6 | from circle_dance.cli.subcommands.listen import ListenSubcommand 7 | from circle_dance.cli.subcommands.play import PlaySubcommand 8 | 9 | __all__ = ["BaseSubcommand", "classproperty", "PlaySubcommand", "ListenSubcommand"] 10 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [tool.poetry] 2 | name = "circle-dance" 3 | version = "0.1.0" 4 | description = "Music Visualizer" 5 | authors = ["Oskar Maier "] 6 | license = "GPL-3.0-or-later" 7 | readme = "README.md" 8 | 9 | [tool.poetry.dependencies] 10 | python = "^3.10" 11 | pygame = "^2.6.1" 12 | librosa = "^0.10.2.post1" 13 | pyaudio = "^0.2.14" 14 | audioflux = "^0.1.9" 15 | 16 | [tool.poetry.group.dev.dependencies] 17 | black = "^24.10.0" 18 | pre-commit = "^4.0.1" 19 | 20 | [tool.poetry.scripts] 21 | circle_dance = "circle_dance.cli.entrypoint:main" 22 | 23 | [build-system] 24 | requires = ["poetry-core"] 25 | build-backend = "poetry.core.masonry.api" 26 | 27 | [tool.black] 28 | line-length = 119 29 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/config.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: configuration 2 | 3 | # Colors 4 | BLACK = (0, 0, 0) 5 | PINK = (255, 105, 180) 6 | sheet_colors = [ 7 | (255, 0, 126), 8 | (221, 7, 127), 9 | (187, 14, 128), 10 | (152, 21, 128), 11 | (118, 28, 129), 12 | (84, 35, 130), 13 | ] 14 | 15 | 16 | # rotation 17 | rotation_period = 10 # seconds for a full rotation 18 | 19 | # sheets 20 | n_notes: int = 12 # including half-notes 21 | n_sheet_lines: int = n_notes // 2 # corresponds to full notes 22 | max_dist_between_sheet_lines: int = ( 23 | 15 # maximum distance between each two lines of a sheet; to avoid too spread out sheet lines when few sheets on canvas 24 | ) 25 | 26 | # canvas 27 | radius_margin_outer: int = 100 # space in pixels to leave between screen and first sheet 28 | radius_margin_inner: int = 50 # space in pixels to leave between screen and last sheet 29 | n_lines_space_between_sheets: int = 3 # number of sheet lines of space to leave between each two sheets 30 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | default_stages: [pre-commit] 2 | repos: 3 | - repo: https://github.com/pre-commit/pre-commit-hooks 4 | rev: v4.5.0 5 | hooks: 6 | - id: check-added-large-files 7 | args: ["--maxkb=2000"] 8 | - id: check-merge-conflict 9 | - id: check-yaml 10 | - id: end-of-file-fixer 11 | - id: trailing-whitespace 12 | - id: debug-statements 13 | 14 | - repo: https://github.com/pycqa/isort 15 | rev: "5.13.2" 16 | hooks: 17 | - id: isort 18 | args: ["--profile", "black", "--line-length=88"] 19 | 20 | - repo: https://github.com/psf/black 21 | rev: 24.10.0 22 | hooks: 23 | - id: black 24 | args: ["--line-length=119"] 25 | 26 | - repo: https://github.com/hadialqattan/pycln 27 | rev: "v2.4.0" 28 | hooks: 29 | - id: pycln 30 | args: ["--all"] 31 | 32 | - repo: https://github.com/Yelp/detect-secrets 33 | rev: v1.4.0 34 | hooks: 35 | - id: detect-secrets 36 | args: ["--exclude-files", ".*\\.ipynb"] 37 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/__init__.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization 2 | 3 | # warning: import order matters here, hierachical from lowest to highest 4 | from circle_dance.visualize.circular_sheet.pointer import Pointer # isort:skip 5 | from circle_dance.visualize.circular_sheet.notes import ( # isort:skip 6 | ArcNote, 7 | ArcNote_Legacy, 8 | DotNote, 9 | Note, 10 | SimpleArcNote, 11 | ) 12 | from circle_dance.visualize.circular_sheet.note_pool import ( # isort:skip 13 | ArcNotePool, 14 | ArcNotePool_Legacy, 15 | DotNotePool, 16 | NotePool, 17 | SimpleArcNotePool, 18 | ) 19 | from circle_dance.visualize.circular_sheet.sheet import Sheet # isort:skip 20 | from circle_dance.visualize.circular_sheet.canvas import Canvas # isort:skip 21 | 22 | __all__ = [ 23 | "Pointer", 24 | "Note", 25 | "DotNote", 26 | "ArcNote", 27 | "SimpleArcNote", 28 | "ArcNote_Legacy", 29 | "NotePool", 30 | "DotNotePool", 31 | "ArcNotePool", 32 | "SimpleArcNotePool", 33 | "ArcNotePool_Legacy", 34 | "Sheet", 35 | "Canvas", 36 | ] 37 | -------------------------------------------------------------------------------- /circle_dance/game/modules/__init__.py: -------------------------------------------------------------------------------- 1 | # collection of game modules 2 | # each game module adds a functionality to the game 3 | # modules are the objects that stitch together all other elements, such as audio readers, processing, and visualization 4 | 5 | from circle_dance.game.modules.base import BaseModule 6 | from circle_dance.game.modules.circular_sheet_file import ( 7 | ArcNotesOnCircularSheet, 8 | DotNotesOnCircularSheet, 9 | SimpleArcNotesOnCircularSheet, 10 | ) 11 | from circle_dance.game.modules.circular_sheet_stream import ( 12 | ArcNotesOnCircularSheetStream, 13 | CircularSheetStream, 14 | DotNotesOnCircularSheetStream, 15 | SimpleArcNotesOnCircularSheetStream, 16 | ) 17 | from circle_dance.game.modules.music_player import MusicPlayer 18 | 19 | __all__ = [ 20 | "BaseModule", 21 | "DotNotesOnCircularSheet", 22 | "ArcNotesOnCircularSheet", 23 | "SimpleArcNotesOnCircularSheet", 24 | "CircularSheetStream", 25 | "DotNotesOnCircularSheetStream", 26 | "ArcNotesOnCircularSheetStream", 27 | "SimpleArcNotesOnCircularSheetStream", 28 | "MusicPlayer", 29 | ] 30 | -------------------------------------------------------------------------------- /circle_dance/cli/subcommands/base.py: -------------------------------------------------------------------------------- 1 | # the subcommand interface 2 | 3 | import abc 4 | import argparse 5 | 6 | 7 | class classproperty: 8 | "Implementation of @classproperty, as the native @classmethod is depreciated in Python 3.11." 9 | 10 | def __init__(self, func): 11 | self.func = func 12 | 13 | def __get__(self, obj, cls=None): 14 | return self.func(cls) 15 | 16 | 17 | class BaseSubcommand(abc.ABC): 18 | "Subcommand static interface definition." 19 | 20 | @classproperty 21 | @abc.abstractmethod 22 | def name(cls) -> str: 23 | "Subcommand name" 24 | pass 25 | 26 | @classproperty 27 | @abc.abstractmethod 28 | def help(cls) -> str: 29 | "Short description of what the subcommand does" 30 | pass 31 | 32 | @classproperty 33 | @abc.abstractmethod 34 | def description(cls) -> str: 35 | "Long description of what the subcommand does" 36 | pass 37 | 38 | @staticmethod 39 | @abc.abstractmethod 40 | def add_arguments(parser: argparse.ArgumentParser) -> None: 41 | "Add arguments to the subcommand parser." 42 | pass 43 | 44 | @staticmethod 45 | @abc.abstractmethod 46 | def run(args: argparse.Namespace) -> None: 47 | "Run the subcommand" 48 | pass 49 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/pointer.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: rotating pointer 2 | 3 | import math 4 | 5 | import pygame 6 | 7 | from circle_dance.visualize import Drawable 8 | from circle_dance.visualize.circular_sheet import utils 9 | from circle_dance.visualize.types import T_COLOR 10 | 11 | LINE_WIDTH = 2 12 | 13 | 14 | class Pointer(Drawable): 15 | def __init__(self, surface: pygame.Surface, radius: int, color: T_COLOR): 16 | """A rotating pointer that indicates the current position in the circular sheet.""" 17 | self.surface = surface 18 | self.center = (surface.get_width() // 2, surface.get_height() // 2) 19 | self.radius = radius 20 | self.color = color 21 | 22 | def draw(self, t: float): 23 | """Draw the pointer at the position corresponding to `t`.""" 24 | angle = utils.get_angle_at_time(t) 25 | self.__draw_pointer(angle) 26 | 27 | def __draw_pointer(self, angle: float): 28 | """Draw a line from the center to the radius' circumference at the current angle. 29 | 30 | Args: 31 | angle: position of the line, expressed as a circle's angle in radians 32 | """ 33 | end_x = self.center[0] + self.radius * math.cos(angle) 34 | end_y = self.center[1] + self.radius * math.sin(angle) 35 | pygame.draw.line(self.surface, self.color, self.center, (end_x, end_y), LINE_WIDTH) 36 | -------------------------------------------------------------------------------- /circle_dance/game/modules/music_player.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | from circle_dance.game import Game 4 | from circle_dance.game.modules import BaseModule 5 | 6 | 7 | class MusicPlayer(BaseModule): 8 | 9 | def __init__(self, fn: str): 10 | """Music player module. 11 | 12 | This game module plays a song while the game runs. 13 | It starts playing at the beginning of the game's clock. 14 | It signals for game termination once the song has finished playing. 15 | 16 | !TBD: 17 | - allow for looping (init parameter) 18 | - allow to disable termination request on finish 19 | 20 | Args: 21 | fn: the song file 22 | """ 23 | self.fn = fn 24 | 25 | def _setup(self, g: Game): 26 | """Setup the music player.""" 27 | pygame.mixer.init() 28 | pygame.mixer.music.load(self.fn) 29 | 30 | def _teardown(self, g: Game): 31 | """Teardown the music player.""" 32 | pygame.mixer.stop() 33 | pygame.mixer.quit() 34 | 35 | def _pre_run(self, g: Game, clock: float): 36 | """Pre-run the music player.""" 37 | pygame.mixer.music.play() 38 | 39 | def _post_run(self, g: Game, clock: float): 40 | """Pre-run the music player.""" 41 | pygame.mixer.music.stop() 42 | 43 | def _update(self, g: Game, clock: float): 44 | pass 45 | 46 | def _should_terminate(self, g: Game, clock: float) -> bool: 47 | """Check if the game should terminate because the music has finished.""" 48 | return not pygame.mixer.music.get_busy() 49 | -------------------------------------------------------------------------------- /circle_dance/cli/entrypoint.py: -------------------------------------------------------------------------------- 1 | # main CLI entrypoint, actual work is handled by subcommands 2 | 3 | import argparse 4 | import logging 5 | 6 | from circle_dance.cli import subcommands 7 | 8 | logger = logging.getLogger(__name__) 9 | 10 | 11 | def main(): 12 | args = get_parser().parse_args() 13 | 14 | # handle global arguments 15 | if args.debug: 16 | logging.basicConfig(level=logging.DEBUG) 17 | elif args.verbose: 18 | logging.basicConfig(level=logging.INFO) 19 | else: 20 | logging.basicConfig(level=logging.WARNING) 21 | 22 | # call subcommand entrypoint 23 | args.func(args) 24 | 25 | 26 | def get_parser() -> argparse.ArgumentParser: 27 | parser = argparse.ArgumentParser(prog="circle_dance", description="Visualize audio notes on a circular sheet.") 28 | parser.add_argument("--verbose", action="store_true", help="Enable verbose mode.") 29 | parser.add_argument("--debug", action="store_true", help="Enable debug mode.") 30 | 31 | subparsers = parser.add_subparsers(description="Choose a functionality.", required=True) # , metavar="") 32 | 33 | # add subparsers 34 | __register_subcommand(subparsers, subcommands.PlaySubcommand) 35 | __register_subcommand(subparsers, subcommands.ListenSubcommand) 36 | 37 | return parser 38 | 39 | 40 | def __register_subcommand(sps: argparse._SubParsersAction, sc: type[subcommands.BaseSubcommand]): 41 | sc_parser = sps.add_parser( 42 | sc.name, 43 | help=sc.help, 44 | description=sc.description, 45 | ) 46 | sc.add_arguments(sc_parser) 47 | sc_parser.set_defaults(func=sc.run) 48 | 49 | 50 | if __name__ == "__main__": 51 | main() 52 | -------------------------------------------------------------------------------- /circle_dance/game/modules/base.py: -------------------------------------------------------------------------------- 1 | # base module interface 2 | # only used for convenience, modules don't have to implement this and can register their callbacks otherwise 3 | 4 | import abc 5 | 6 | from circle_dance.game import Game 7 | 8 | 9 | class BaseModule(abc.ABC): 10 | """Convenience module base class. 11 | 12 | Simply subclass and define all the internal callback methods. 13 | When used, initialize and call `register_callbacks()` on the Game. 14 | 15 | If a callback is not needed, implement it with `pass` as body. 16 | """ 17 | 18 | @abc.abstractmethod 19 | def _setup(self, g: Game): 20 | """Setup the module.""" 21 | pass 22 | 23 | @abc.abstractmethod 24 | def _teardown(self, g: Game): 25 | """Teardown module.""" 26 | pass 27 | 28 | @abc.abstractmethod 29 | def _pre_run(self, g: Game, clock: float): 30 | """Initializations to perform at clock = 0.""" 31 | pass 32 | 33 | @abc.abstractmethod 34 | def _post_run(self, g: Game, clock: float): 35 | """Teardowns to perform at last clock tick.""" 36 | pass 37 | 38 | @abc.abstractmethod 39 | def _update(self, g: Game, clock: float): 40 | "Perform update of module, potentially depending on clock, during run." 41 | pass 42 | 43 | @abc.abstractmethod 44 | def _should_terminate(self, g: Game, clock: float) -> bool: 45 | """Request game termination.""" 46 | pass 47 | 48 | def register_callbacks(self, g: Game): 49 | """Register the module's callbacks with the game.""" 50 | g.register_setup_callback(self._setup) 51 | g.register_teardown_callback(self._teardown) 52 | g.register_pre_run_callback(self._pre_run) 53 | g.register_post_run_callback(self._post_run) 54 | g.register_update_callback(self._update) 55 | g.register_should_terminate_callback(self._should_terminate) 56 | -------------------------------------------------------------------------------- /circle_dance/audio/process/note_onsets.py: -------------------------------------------------------------------------------- 1 | import audioflux as af 2 | import librosa 3 | import numpy as np 4 | 5 | 6 | def extract_note_onsets(y, sr: float, threshold: float = 0.9): 7 | """Extract the note onset from each frame of audio data. 8 | 9 | Args: 10 | y: audio data 11 | sr: sampling rate of the audio data 12 | threshold: the chroma energy threshold for considering a note as active; between 0 and 1 13 | 14 | Returns: 15 | the detect N note onsets and their onset time; shape=(N, 4), 16 | with columns=(note_id, onset(sec), np.nan, chroma_energy[0,1]) 17 | """ 18 | # Compute the chromagram 19 | # note: audioflux is 10x faster than librosa 20 | obj = af.CQT(num=12 * 7, samplate=int(sr), low_fre=af.utils.note_to_hz("C1"), bin_per_octave=12, slide_length=512) 21 | chroma = obj.chroma(obj.cqt(y), chroma_num=12) 22 | # chroma = librosa.feature.chroma_cqt(y=y, sr=sr, n_chroma=12) 23 | 24 | # Compute onset strength 25 | onset_env = librosa.onset.onset_strength(y=y, sr=sr) 26 | 27 | # Detect note onsets 28 | onset_frames = librosa.onset.onset_detect(onset_envelope=onset_env, sr=sr, normalize=True, backtrack=True) 29 | 30 | # Extract notes at onset frames 31 | notes_with_onsets = [] 32 | for frame in onset_frames: 33 | chroma_frame = chroma[:, frame] 34 | frame_time = librosa.frames_to_time(frame, sr=sr) 35 | 36 | # Find all notes above the threshold 37 | active_note_found = False 38 | for i, magnitude in enumerate(chroma_frame): 39 | if magnitude > threshold: 40 | notes_with_onsets.append((i % 12, frame_time, np.nan, magnitude)) 41 | active_note_found = True 42 | 43 | # If no notes are above threshold, take the highest one 44 | if not active_note_found: 45 | max_index = int(np.argmax(chroma_frame)) 46 | notes_with_onsets.append((max_index % 12, frame_time, np.nan, chroma_frame[max_index])) 47 | 48 | return np.asarray(notes_with_onsets) 49 | -------------------------------------------------------------------------------- /circle_dance/cli/subcommands/listen.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from circle_dance.cli.subcommands import BaseSubcommand, classproperty 4 | from circle_dance.game import Game, modules 5 | 6 | 7 | def main(): 8 | print(ListenSubcommand.name) 9 | args = get_parser().parse_args() 10 | ListenSubcommand.run(args) 11 | 12 | 13 | def get_parser() -> argparse.ArgumentParser: 14 | parser = argparse.ArgumentParser(prog=ListenSubcommand.name, description=ListenSubcommand.description) 15 | ListenSubcommand.add_arguments(parser) 16 | return parser 17 | 18 | 19 | class ListenSubcommand(BaseSubcommand): 20 | "The listen subcommand implementation." 21 | 22 | _name = "listen" 23 | _help = "Listen to the OS's default input device and visualize the note on a circular music sheet." 24 | _description = "Listen to the OS's default input device and visualize the note on a circular music sheet." 25 | 26 | @classproperty 27 | def name(cls) -> str: 28 | return cls._name 29 | 30 | @classproperty 31 | def help(cls) -> str: 32 | return cls._help 33 | 34 | @classproperty 35 | def description(cls) -> str: 36 | return cls._description 37 | 38 | @staticmethod 39 | def add_arguments(parser: argparse.ArgumentParser) -> None: 40 | parser.add_argument("-t", "--threshold", type=float, default=0.75, help="Threshold for note detection.") 41 | parser.add_argument( 42 | "--note-type", choices=["dot", "arc"], default="dot", help="Type of note to use in visualization." 43 | ) 44 | 45 | @staticmethod 46 | def run(args: argparse.Namespace) -> None: 47 | g = Game() 48 | 49 | circular_sheet: modules.BaseModule 50 | if args.note_type == "dot": 51 | circular_sheet = modules.DotNotesOnCircularSheetStream(threshold=args.threshold) 52 | elif args.note_type == "sarc": 53 | circular_sheet = modules.SimpleArcNotesOnCircularSheetStream(threshold=args.threshold) 54 | else: 55 | circular_sheet = modules.ArcNotesOnCircularSheetStream(threshold=args.threshold) 56 | circular_sheet.register_callbacks(g) 57 | 58 | g.run() 59 | 60 | 61 | if __name__ == "__main__": 62 | main() 63 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/sheet.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: note sheet 2 | 3 | import pygame 4 | 5 | from circle_dance.visualize import Drawable 6 | from circle_dance.visualize.circular_sheet import NotePool 7 | from circle_dance.visualize.types import T_COLOR 8 | 9 | LINE_WIDTH = 1 10 | 11 | 12 | class Sheet(Drawable): 13 | def __init__( 14 | self, 15 | surface: pygame.Surface, 16 | radius_outer: int, 17 | n_sheet_lines: int, 18 | dist_between_sheet_lines: int, 19 | color: T_COLOR, 20 | note_pool: type[NotePool], 21 | ): 22 | """Define a (circular) sheet music on the screen. 23 | 24 | Draws multiple lines. Can generate notes which are drawn among the lines. 25 | 26 | Args: 27 | screen: surface to draw on 28 | radius_outer: outer radius of the sheet, corresponds to the first line 29 | n_sheet_lines: number of lines in the sheet 30 | dist_between_sheet_lines: distance between each line in the sheet 31 | color: color of the sheet lines 32 | note_pool: NotePool implementation to use for this sheet 33 | """ 34 | super().__init__(surface) 35 | 36 | self.radius_outer = radius_outer 37 | self.n_sheet_lines = n_sheet_lines 38 | self.dist_between_sheet_lines = dist_between_sheet_lines 39 | self.color = color 40 | self.center = (surface.get_width() // 2, surface.get_height() // 2) 41 | 42 | self.note_pool = note_pool( 43 | self.surface, 44 | self.radius_outer, 45 | self.dist_between_sheet_lines // 2, # two notes per line, as half-tones are possible 46 | self.color, 47 | ) 48 | 49 | def draw(self, t: float) -> None: 50 | self.__draw_sheet() 51 | self.note_pool.draw(t) 52 | 53 | def __draw_sheet(self): 54 | """Draw the lines of a circular music sheet. 55 | 56 | Draws `n_sheet_lines` of color `color` starting at `radius_outer` inwards with `dist_between_sheet_lines` between the lines. 57 | """ 58 | for j in range(self.n_sheet_lines): 59 | pygame.draw.circle( 60 | self.surface, 61 | self.color, 62 | self.center, 63 | self.radius_outer - j * self.dist_between_sheet_lines, 64 | width=LINE_WIDTH, 65 | ) 66 | -------------------------------------------------------------------------------- /circle_dance/cli/subcommands/play.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | 3 | from circle_dance.cli.subcommands import BaseSubcommand, classproperty 4 | from circle_dance.game import Game, modules 5 | 6 | 7 | def main(): 8 | print(PlaySubcommand.name) 9 | args = get_parser().parse_args() 10 | PlaySubcommand.run(args) 11 | 12 | 13 | def get_parser() -> argparse.ArgumentParser: 14 | parser = argparse.ArgumentParser(prog=PlaySubcommand.name, description=PlaySubcommand.description) 15 | PlaySubcommand.add_arguments(parser) 16 | return parser 17 | 18 | 19 | class PlaySubcommand(BaseSubcommand): 20 | "The play subcommand implementation." 21 | 22 | _name = "play" 23 | _help = "Play a song and visualize the note on a circular music sheet." 24 | _description = "Play a song and visualize the note on a circular music sheet." 25 | 26 | @classproperty 27 | def name(cls) -> str: 28 | return cls._name 29 | 30 | @classproperty 31 | def help(cls) -> str: 32 | return cls._help 33 | 34 | @classproperty 35 | def description(cls) -> str: 36 | return cls._description 37 | 38 | @staticmethod 39 | def add_arguments(parser: argparse.ArgumentParser) -> None: 40 | parser.add_argument("filename", help="Song to play.") 41 | parser.add_argument("-t", "--threshold", type=float, default=0.75, help="Threshold for note detection.") 42 | parser.add_argument( 43 | "--note-type", choices=["dot", "arc", "sarc"], default="dot", help="Type of note to use in visualization." 44 | ) 45 | 46 | @staticmethod 47 | def run(args: argparse.Namespace) -> None: 48 | g = Game() 49 | 50 | circular_sheet: modules.BaseModule 51 | if args.note_type == "dot": 52 | circular_sheet = modules.DotNotesOnCircularSheet(args.filename, threshold=args.threshold) 53 | elif args.note_type == "sarc": 54 | circular_sheet = modules.SimpleArcNotesOnCircularSheet(args.filename, threshold=args.threshold) 55 | else: 56 | circular_sheet = modules.ArcNotesOnCircularSheet(args.filename, threshold=args.threshold) 57 | music_player = modules.MusicPlayer(args.filename) 58 | 59 | circular_sheet.register_callbacks(g) 60 | music_player.register_callbacks( 61 | g 62 | ) # note: order can matter; we want music to start after all other setup / pre-run is done 63 | 64 | g.run() 65 | 66 | 67 | if __name__ == "__main__": 68 | main() 69 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | 2 | # Ideas, notes and more 3 | 4 | ## Ideas 5 | - Write equalizer similar thing to separate high / mid / low and show each on one sheet 6 | - Normalize chroma, when running on chunks, with running average; otherwise it picks up noise due to normalization on chromagram 7 | - Add some controls to player: one button to see what keys are available; then connect all important parameters to keys for stream processing 8 | - Optimize the hell out of ArcNotes 9 | 10 | ## Todos 11 | - Make that pygame message is not printed (either set env var to suppress or redirect output on import... both not good solutions) 12 | - Write documentation with overview over the library's parts 13 | - Write some usage examples 14 | - Make fullscreen optional / flag, otherwise can provide width/height 15 | - Make clones=int an arg and use it 16 | - Allow to list and select audio source devices 17 | 18 | ## Notes 19 | 20 | ### Good settings for chroma_CQT 21 | CHUNK = 1024 # multiple of SLIDE_LENGTH 22 | CARRYOVER = 10 23 | REFILL = 1 24 | LOOPS = 100 * 5 25 | SLIDE_LENGTH = 512 26 | 27 | 28 | ### Insights into required speed 29 | - !WARNING: When processing runtime > buffer_replenish_multiplier * CHUNK / RATE, then the notes will slowly get more and more delayed 30 | - potential solution: discard older notes, always empty audio buffer until no more to get 31 | - !WARNING: buffer_replenish_multiplier * CHUNK / RATE is minimum delay between displays - should be <= 0.02s to perceive as real time 32 | 33 | ### How to connect an (audio) sink to a source and more (in Windows VirtualCable) 34 | 1. Create virtual cables, ny sound played to "virtual_speaker" will be sent to "virtual_mic" 35 | ``` 36 | pactl load-module module-null-sink sink_name="virtual_speaker" sink_properties=device.description="virtual_speaker" 37 | pactl load-module module-remap-source master="virtual_speaker.monitor" source_name="virtual_mic" source_properties=device.description="virtual_mic" 38 | ``` 39 | 2. Connect to your sound card to also listen to whatever is played 40 | ``` 41 | pactl load-module module-loopback source="virtual_mic" sink=alsa_output.pci-0000_00_1f.3-platform-skl_hda_dsp_generic.HiFi__hw_sofhdadsp__sink 42 | pactl load-module module-loopback source="virtual_mic" sink=alsa_output.pci-0000_00_1f.3.analog-stereo 43 | ``` 44 | 3. Select "virtual_speaker" resp. "virtual_mic" as your default devices in the audio settings; p.open() will automatically use the default input device 45 | 46 | Further commands to remember 47 | ``` 48 | pactl list sources # prints audio sources (micros and co) / in 49 | pactl list sinks # prints audio sinks (speakers and co) / out 50 | pactl load-module module-loopback # enable loopback for pulseaudio to listen to the output of the PC 51 | pactl load-module module-lopback latency_msec=1 52 | pactl list modules # list all modules with their ids 53 | pactl info 34 # print details about module with this id 54 | pactl unload-module 24 # unload module with this id 55 | ``` 56 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/canvas.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: main canvas 2 | 3 | import pygame 4 | 5 | from circle_dance.visualize import Drawable 6 | from circle_dance.visualize.circular_sheet import NotePool, Pointer, Sheet, config 7 | from circle_dance.visualize.types import T_COLOR 8 | 9 | 10 | class Canvas(Drawable): 11 | def __init__( 12 | self, surface: pygame.Surface, n_sheets: int, note_pool: type[NotePool], bg_color: T_COLOR = config.BLACK 13 | ): 14 | """The main circular sheet visualization canvas. 15 | 16 | Takes care of coordinating all the contained components. 17 | 18 | Args: 19 | surface: surface to draw on 20 | n_sheets: no of circular sheets to display and support 21 | note_pool: NotePool implementation to use for the sheets 22 | bg_color: background color of the canvas 23 | """ 24 | super().__init__(surface) 25 | 26 | assert n_sheets > 0, "At least one sheet must be drawn." 27 | 28 | self.bg_color = bg_color 29 | self.radius_outer = ( 30 | min(surface.get_width(), surface.get_height()) // 2 - config.radius_margin_outer 31 | ) # outermost radius to draw in 32 | self.radius_inner = config.radius_margin_inner # innermost radius to draw in 33 | 34 | # surface the sub-components draw on, with alpha support 35 | self.surface_components = pygame.Surface((surface.get_width(), surface.get_height()), pygame.SRCALPHA) 36 | 37 | # init sub-components 38 | self.sheets: list[Sheet] = [] 39 | dist_between_sheet_lines = min( 40 | config.max_dist_between_sheet_lines, 41 | ( 42 | (self.radius_outer - self.radius_inner) 43 | // n_sheets 44 | // (config.n_sheet_lines + config.n_lines_space_between_sheets) 45 | ), 46 | ) 47 | for i in range(n_sheets): 48 | sheet_radius_outer = self.radius_outer - i * config.n_sheet_lines * ( 49 | dist_between_sheet_lines + config.n_lines_space_between_sheets 50 | ) 51 | self.sheets.append( 52 | Sheet( 53 | self.surface_components, 54 | sheet_radius_outer, 55 | config.n_sheet_lines, 56 | dist_between_sheet_lines, 57 | config.sheet_colors[i], 58 | note_pool, 59 | ) 60 | ) 61 | 62 | self.pointer: Pointer = Pointer(self.surface_components, self.radius_outer, config.PINK) 63 | 64 | def draw(self, t: float) -> None: 65 | self.surface.fill(self.bg_color) # fill in surface 66 | self.surface_components.fill((0, 0, 0, 0)) # clear sub-components surface 67 | 68 | self.pointer.draw(t) 69 | for sheet in self.sheets: 70 | sheet.draw(t) 71 | 72 | # blit the sub-components surface onto the surface 73 | self.surface.blit(self.surface_components, self.surface_components.get_rect()) 74 | 75 | def add_note(self, sheet_id: int, note: int, onset: float, conclusion: float, energy: float): 76 | "Add a note to an underlying sheet." 77 | self.sheets[sheet_id].note_pool.add_note(note, onset, conclusion, energy) 78 | -------------------------------------------------------------------------------- /circle_dance/audio/read/callbacks.py: -------------------------------------------------------------------------------- 1 | # audio stream callback functions to be used in the stream reader 2 | # these wrap the audio processing functionality to be usable in the stream_reader 3 | 4 | import logging 5 | 6 | import numpy.typing as npt 7 | 8 | from circle_dance.audio import process 9 | 10 | logger = logging.getLogger(__name__) 11 | 12 | 13 | # Note: prefers steam_reader with 14 | # buffer_replenish_multiplier = 5 15 | # buffer_carryover_multiplier = 20 16 | def extract_node_onsets_callback( 17 | buffer: npt.NDArray, 18 | sr: float, 19 | stream_clock: float, 20 | carryover_samples: int, 21 | carryover_time_sec: float, 22 | threshold: float = 0.99, 23 | ) -> npt.NDArray: 24 | """ 25 | Extracts note onsets from an audio buffer and adds them to a queue. 26 | 27 | This function processes an audio buffer to detect note onsets and adds the detected notes to a queue. 28 | It adjusts the onset times to account for the carryover samples from the previous iteration/buffer. 29 | 30 | Usage: 31 | `notes_producer(lambda *args, **kwargs: process_buffer_callback(*args, **kwargs, threshold=0.9), ...)` 32 | 33 | Args: 34 | queue: The queue to put the detected notes into. 35 | buffer: The audio buffer containing the audio data. First part is carried over form previous iteration/buffer, 36 | the remaining samples are new. 37 | sr: The sampling rate of the audio. 38 | stream_clock: The current position in the audio stream after the carry over samples, in seconds. 39 | carryover_samples: the number of samples at the beginning of the buffer that are repeated the previous 40 | iteration/buffer 41 | carryover_time_sec: the time in seconds of the carryover samples 42 | threshold: The energy threshold for considering a note as active, between 0 and 1. 43 | 44 | Returns: 45 | Notes cleaned from carryover effects. 46 | """ 47 | # extract notes 48 | notes_with_onsets = process.extract_note_onsets(buffer.astype(float), sr=sr, threshold=threshold) 49 | 50 | # remove carryover part and adjust times 51 | notes_with_onsets[:, 1:2] -= carryover_time_sec # adjust onset times 52 | notes_with_onsets = notes_with_onsets[notes_with_onsets[:, 1] > 0] # remove notes wiht onset in the past 53 | 54 | # add stream clock to times to get real clock times of notes 55 | notes_with_onsets[:, 1:2] += stream_clock 56 | 57 | return notes_with_onsets 58 | 59 | 60 | # Note: prefers steam_reader with 61 | # buffer_replenish_multiplier = 1 62 | # buffer_carryover_multiplier = 20 63 | def extract_note_durations_callback( 64 | buffer: npt.NDArray, 65 | sr: float, 66 | stream_clock: float, 67 | carryover_samples: int, 68 | carryover_time_sec: float, 69 | threshold: float = 0.99, 70 | ) -> npt.NDArray: 71 | # extract notes 72 | notes_with_durations = process.extract_note_durations(buffer.astype(float), sr=sr, thr=threshold) 73 | 74 | # remove carryover part and adjust times 75 | notes_with_durations[:, 1:3] -= carryover_time_sec # adjust onset and conclusion times 76 | notes_with_durations = notes_with_durations[ 77 | notes_with_durations[:, 2] > 0 78 | ] # remove notes with duration in the past 79 | notes_with_durations = notes_with_durations.clip(min=0) # clip onset 80 | 81 | # add stream clock to times to get real clock times of notes 82 | notes_with_durations[:, 1:3] += stream_clock 83 | 84 | return notes_with_durations 85 | -------------------------------------------------------------------------------- /circle_dance/audio/process/note_durations.py: -------------------------------------------------------------------------------- 1 | import audioflux as af 2 | import librosa 3 | import numpy as np 4 | import scipy 5 | 6 | 7 | def extract_note_durations(y, sr: float, thr: float = 0.9, slide_length: int = 512): 8 | """Extract from an audio chunk all notes/sounds with chroma energy above the threshold and returns their duration 9 | and energy. 10 | 11 | Note: 12 | This does not detect note onsets, just the duration of a certain chroma in the chromagram. 13 | 14 | Note: 15 | slide_length in audioflux = hop_length in librosa 16 | 17 | Args: 18 | y: audio data 19 | sr: sampling rate of the audio data 20 | thr: the chroma energy threshold for considering a note as active; between 0 and 1 21 | slide_length: the slide length used to compute the chromagram 22 | 23 | Returns: 24 | the detect N notes and their duration; shape=(N, 4), 25 | with columns=(note_id, onset(sec), conclusion(sec), mean_chroma_energy[0,1]) 26 | """ 27 | # calculate chromagram 28 | obj = af.CQT( 29 | num=12 * 7, 30 | samplate=int(sr), 31 | low_fre=af.utils.note_to_hz("C1"), 32 | bin_per_octave=12, 33 | slide_length=slide_length, 34 | # is_scale=False, 35 | # thresh=0.5, 36 | ) 37 | chromagram = obj.chroma(obj.cqt(y), chroma_num=12) # , norm_type=af.type.ChromaDataNormalType.NONE) 38 | 39 | # prepare 40 | chrom_bin_time_delta = slide_length / sr 41 | structure_element = np.asarray([[False, False, False], [True, True, True], [False, False, False]]) 42 | n_chromas, n_chroma_bins = chromagram.shape 43 | 44 | # convert chroma bins to their start times (in sec) 45 | chroms_bin_start_times = librosa.frames_to_time(range(n_chroma_bins), sr=sr, hop_length=slide_length) 46 | 47 | # binary morphology magic, applied on each row separately, due to 1D structure element 48 | chroma_thr = chromagram > thr 49 | start_and_end = chroma_thr ^ scipy.ndimage.binary_erosion(chroma_thr, structure=structure_element) 50 | labels, label_count = scipy.ndimage.label(chroma_thr, structure=structure_element) 51 | 52 | if label_count == 0: 53 | return np.empty((0, 4)) 54 | 55 | # extract start and end of each detected stucture 56 | labels_start_end = labels[start_and_end] 57 | times_start_end = np.tile(chroms_bin_start_times, (n_chromas, 1))[start_and_end] 58 | 59 | # pair and deal with fact that we can have single-element structures in the buffer 60 | # can work on whole chroma array at once, as each row has unique labels 61 | i = 0 62 | durations = [] 63 | while i < len(labels_start_end): 64 | if i + 1 < len(labels_start_end) and labels_start_end[i] == labels_start_end[i + 1]: # double label 65 | durations.append((times_start_end[i], times_start_end[i + 1])) 66 | i += 2 67 | else: # single label 68 | durations.append((times_start_end[i], times_start_end[i])) 69 | i += 1 70 | durations_arr = np.asarray(durations) 71 | durations_arr[:, 1] += chrom_bin_time_delta # add chroma bin time to end, as bin time denotes bin start 72 | 73 | # extract node id's and mean chroma energies 74 | note_ids = [] 75 | chroma_energies = [] 76 | for lid in range(label_count): 77 | lmask = labels == (lid + 1) 78 | note_ids.append(np.where(lmask)[0][0]) 79 | chroma_energies.append(chromagram[lmask].mean()) 80 | 81 | # note that time ranges for entries of the same note never overlap 82 | return np.hstack([np.asarray(note_ids).reshape(-1, 1), durations_arr, np.asarray(chroma_energies).reshape(-1, 1)]) 83 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Repository specific ignores 2 | bckup/ 3 | legacy/ 4 | songs/ 5 | #research/ 6 | 7 | # Byte-compiled / optimized / DLL files 8 | __pycache__/ 9 | *.py[cod] 10 | *$py.class 11 | 12 | # C extensions 13 | *.so 14 | 15 | # Distribution / packaging 16 | .Python 17 | build/ 18 | develop-eggs/ 19 | dist/ 20 | downloads/ 21 | eggs/ 22 | .eggs/ 23 | lib/ 24 | lib64/ 25 | parts/ 26 | sdist/ 27 | var/ 28 | wheels/ 29 | share/python-wheels/ 30 | *.egg-info/ 31 | .installed.cfg 32 | *.egg 33 | MANIFEST 34 | 35 | # PyInstaller 36 | # Usually these files are written by a python script from a template 37 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 38 | *.manifest 39 | *.spec 40 | 41 | # Installer logs 42 | pip-log.txt 43 | pip-delete-this-directory.txt 44 | 45 | # Unit test / coverage reports 46 | htmlcov/ 47 | .tox/ 48 | .nox/ 49 | .coverage 50 | .coverage.* 51 | .cache 52 | nosetests.xml 53 | coverage.xml 54 | *.cover 55 | *.py,cover 56 | .hypothesis/ 57 | .pytest_cache/ 58 | cover/ 59 | 60 | # Translations 61 | *.mo 62 | *.pot 63 | 64 | # Django stuff: 65 | *.log 66 | local_settings.py 67 | db.sqlite3 68 | db.sqlite3-journal 69 | 70 | # Flask stuff: 71 | instance/ 72 | .webassets-cache 73 | 74 | # Scrapy stuff: 75 | .scrapy 76 | 77 | # Sphinx documentation 78 | docs/_build/ 79 | 80 | # PyBuilder 81 | .pybuilder/ 82 | target/ 83 | 84 | # Jupyter Notebook 85 | .ipynb_checkpoints 86 | 87 | # IPython 88 | profile_default/ 89 | ipython_config.py 90 | 91 | # pyenv 92 | # For a library or package, you might want to ignore these files since the code is 93 | # intended to run in multiple environments; otherwise, check them in: 94 | # .python-version 95 | 96 | # pipenv 97 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 98 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 99 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 100 | # install all needed dependencies. 101 | #Pipfile.lock 102 | 103 | # poetry 104 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 105 | # This is especially recommended for binary packages to ensure reproducibility, and is more 106 | # commonly ignored for libraries. 107 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 108 | #poetry.lock 109 | 110 | # pdm 111 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 112 | #pdm.lock 113 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 114 | # in version control. 115 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 116 | .pdm.toml 117 | .pdm-python 118 | .pdm-build/ 119 | 120 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 121 | __pypackages__/ 122 | 123 | # Celery stuff 124 | celerybeat-schedule 125 | celerybeat.pid 126 | 127 | # SageMath parsed files 128 | *.sage.py 129 | 130 | # Environments 131 | .env 132 | .venv 133 | env/ 134 | venv/ 135 | ENV/ 136 | env.bak/ 137 | venv.bak/ 138 | 139 | # Spyder project settings 140 | .spyderproject 141 | .spyproject 142 | 143 | # Rope project settings 144 | .ropeproject 145 | 146 | # mkdocs documentation 147 | /site 148 | 149 | # mypy 150 | .mypy_cache/ 151 | .dmypy.json 152 | dmypy.json 153 | 154 | # Pyre type checker 155 | .pyre/ 156 | 157 | # pytype static type analyzer 158 | .pytype/ 159 | 160 | # Cython debug symbols 161 | cython_debug/ 162 | -------------------------------------------------------------------------------- /circle_dance/game/modules/circular_sheet_file.py: -------------------------------------------------------------------------------- 1 | import librosa 2 | 3 | from circle_dance.audio.process import extract_note_durations, extract_note_onsets 4 | from circle_dance.game import Game 5 | from circle_dance.game.modules import BaseModule 6 | from circle_dance.visualize import circular_sheet 7 | 8 | 9 | class CircularSheet(BaseModule): 10 | "Base class for all notes on a circular sheet parsed from a file." 11 | 12 | def __init__(self, fn: str, threshold: float = 0.75, n_clones: int = 1): 13 | """Module that parses an audio file and animate it's notes on a circular sheet. 14 | 15 | Best combined with the `MusicPlayer` module to play the audio while the notes are animated 16 | 17 | Args: 18 | fn: the song file 19 | threshold: the chroma energy threshold for considering a note as active; between 0 and 1 20 | n_clones: number of times to clone the song to produce multiple sheets in the visualization 21 | """ 22 | assert threshold > 0 and threshold <= 1, "threshold must be between 0 and 1" 23 | assert n_clones > 0, "n_clones must be greater than 0" 24 | 25 | self.fn = fn 26 | self.threshold = threshold 27 | self.n_clones = n_clones 28 | 29 | self.canvas: circular_sheet.Canvas 30 | 31 | def _teardown(self, g: Game): 32 | pass 33 | 34 | def _pre_run(self, g: Game, clock: float): 35 | pass 36 | 37 | def _post_run(self, g: Game, clock: float): 38 | pass 39 | 40 | def _update(self, g: Game, clock: float): 41 | "Draw the complete scene onto the screen." 42 | self.canvas.draw(clock) 43 | 44 | def _should_terminate(self, g: Game, clock: float) -> bool: 45 | "Will never request the game to terminate." 46 | return False 47 | 48 | def _load_audio(self): 49 | # load song data 50 | y, sr = librosa.load(self.fn, sr=None) # sr = None means using native sampling rate 51 | ys = [y] * self.n_clones # fake multi-stem data by cloning 52 | return ys, sr 53 | 54 | 55 | class DotNotesOnCircularSheet(CircularSheet): 56 | 57 | def _setup(self, g: Game): 58 | """Parse audio and setup the visualization and note pool.""" 59 | ys, sr = self._load_audio() 60 | 61 | # Init canvas 62 | self.canvas = circular_sheet.Canvas(g.screen, len(ys), circular_sheet.DotNotePool) 63 | 64 | # Extract note onsets 65 | for i in range(len(ys)): 66 | note_onsets = extract_note_onsets(ys[i], sr, threshold=self.threshold) 67 | for note, onset, conclusion, energy in note_onsets: 68 | self.canvas.add_note(i, int(note), onset, conclusion, energy) 69 | 70 | 71 | class SimpleArcNotesOnCircularSheet(CircularSheet): 72 | def _setup(self, g: Game): 73 | """Parse audio and setup the visualization and note pool.""" 74 | ys, sr = self._load_audio() 75 | 76 | # Init canvas 77 | self.canvas = circular_sheet.Canvas(g.screen, len(ys), circular_sheet.SimpleArcNotePool) 78 | 79 | # Extract note onsets 80 | for i in range(len(ys)): 81 | note_onsets = extract_note_durations(ys[i], sr, thr=self.threshold) 82 | for note, onset, conclusion, energy in note_onsets: 83 | self.canvas.add_note(i, int(note), onset, conclusion, energy) 84 | 85 | 86 | class ArcNotesOnCircularSheet(CircularSheet): 87 | def _setup(self, g: Game): 88 | """Parse audio and setup the visualization and note pool.""" 89 | ys, sr = self._load_audio() 90 | 91 | # Init canvas 92 | self.canvas = circular_sheet.Canvas(g.screen, len(ys), circular_sheet.ArcNotePool) 93 | 94 | # Extract note onsets 95 | for i in range(len(ys)): 96 | note_onsets = extract_note_durations(ys[i], sr, thr=self.threshold) 97 | for note, onset, conclusion, energy in note_onsets: 98 | self.canvas.add_note(i, int(note), onset, conclusion, energy) 99 | -------------------------------------------------------------------------------- /DEVELOPMENT.md: -------------------------------------------------------------------------------- 1 | # Development 2 | This document is intended to serve as starting point for developing further components. It explains the main program architecture aka how the components interact with each other, as well as the most important concepts and requirements. 3 | 4 | ## Architecture 5 | The `game` visualizes `audio features` extracted from one or more `audio streams`. The main components and their interactions are shown here. 6 | 7 | **game (main process)** 8 | ``` 9 | canvas = render(game) 10 | blit(screen, canvas) 11 | for _ in range(n_streams): 12 | ft = queue.pop() 13 | canvas = render(ft) 14 | blit(screen, canvas) 15 | ``` 16 | 17 | **processors (one thread per stream)** 18 | ``` 19 | chunk = read_stream() 20 | ft = process(chunk) 21 | queue.put(ft) 22 | ``` 23 | 24 | 25 | ## Runtime requirements 26 | Most components of `circle_dance` are subject to one or two runtime requirements. On the one hand, there is the reading of the `audi stream`: if the read audio samples are not processed fast enough, the input buffer will overflow. On the other hand, the `game`'s screen must update fast enough to ensure a smooth visualization. 27 | 28 | In this section, the two duration requirements are derived and their compuation, which depends on various factors, described. 29 | 30 | ``` 31 | n_streams = {1,2,...} 32 | sr = 42000 | 21000 33 | 34 | n_new_samples = 1024 35 | n_carryover_samples = 2048 36 | chunk = [carryover_samples] + [new_samples] 37 | 38 | max_processing_duration = n_new_samples/sr [s] # speed required such that audio stream buffer doesn't overflow 39 | fps = 30 | 60 # screen update speed required for a smooth visualization 40 | max_render_duration = 1/fps [s] 41 | ``` 42 | 43 | The principal components highlighted in the architecture overview above are subject to these duration constraints. 44 | 45 | ``` 46 | time[process(chunk)] < max_processing_duration 47 | time[render(all)] < min(max_tick_duration, max_render_duration) 48 | time[render(ft)] < min(max_tick_duration, max_render_duration) / n_streams 49 | ``` 50 | 51 | Note that the actual runtimes should be lower than the duration constraints, as the whole program produces some overhead, e.g. for communicating between threads. 52 | 53 | ### Exemplary runtime requirements 54 | 55 | ``` 56 | n_streams = 1 57 | sr = 42000 58 | n_new_samples = 1024 59 | n_carryover_samples = 2048 60 | fps = 30 61 | 62 | max_processing_duration = 0.024380952s = 24.38ms 63 | max_render_duration = 0.033333333s = 33.33ms 64 | ``` 65 | 66 | ``` 67 | n_new_samples = 2048 68 | 69 | max_processing_duration = 0.048761905s = 48.76ms 70 | ``` 71 | 72 | ``` 73 | n_new_samples = 512 74 | 75 | max_processing_duration = 0.012190476s = 12.19ms 76 | ``` 77 | 78 | ``` 79 | fps = 60 80 | 81 | max_render_duration = 0.016666667 = 16.66ms 82 | ``` 83 | 84 | ## Alternative architecture 85 | By moving the `audio feature` renderers into thread workers, the runtime requirements might be loosened somewhat in the case of multiple input streams. 86 | 87 | **game (main process)** 88 | ``` 89 | canvas = render(game) 90 | blit(screen, canvas) 91 | 92 | for t in audio_feature_threads: 93 | t.run() 94 | 95 | canvases = [t.wait() for t in audio_feature_threads] 96 | for canvas in canvases: 97 | blit(screen, canvas) 98 | ``` 99 | 100 | **audio feature renderer (one thread per renderer)** 101 | ``` 102 | ft = queue.pop() 103 | canvas = render(ft) 104 | ``` 105 | 106 | **processors (one thread per stream)** 107 | ``` 108 | chunk = read_stream() 109 | ft = process(chunk) 110 | queue.put(ft) 111 | ``` 112 | 113 | Note that a single processor can be linked to multiple audio feature renderers via dedicated queues. 114 | 115 | In such a configuration, the runtime requirements qould change to: 116 | 117 | ``` 118 | time[process(chunk)] < max_processing_duration 119 | time[render(all)] < min(max_tick_duration, max_render_duration) 120 | time[render(ft)] < time[render(all)] < min(max_tick_duration, max_render_duration) 121 | ``` 122 | -------------------------------------------------------------------------------- /circle_dance/visualize/draw.py: -------------------------------------------------------------------------------- 1 | # general shared drawing functions 2 | import numpy as np 3 | import numpy.typing as npt 4 | import pygame 5 | 6 | 7 | def draw_circle_alpha(surface, color, center, radius): 8 | "Helper function to draw a circle with alpha in pygame." 9 | target_rect = pygame.Rect(center, (0, 0)).inflate((radius * 2, radius * 2)) 10 | shape_surf = pygame.Surface(target_rect.size, pygame.SRCALPHA) 11 | pygame.draw.circle(shape_surf, color, (radius, radius), radius) 12 | surface.blit(shape_surf, target_rect) 13 | 14 | 15 | def draw_cone_arc( 16 | image: npt.NDArray, 17 | center: tuple[float, float], 18 | radius: float, 19 | start_angle_rad: float, 20 | end_angle_rad: float, 21 | start_width: float, 22 | end_width: float, 23 | color: int = 255, 24 | ): 25 | """ 26 | Draw a solid-color cone-shaped arc on an image. 27 | 28 | Destructively paints on the image, replacing all values under the arc pixels. 29 | 30 | Starts the arc at `start_angle` and ends at `end_angle`. The width of the arc at each point is determined by the 31 | `start_width` and `end_width` parameters. The width is linearly interpolated between these values. 32 | 33 | The arc is drawn in clock-wise direction. 34 | 35 | Args: 36 | image: NumPy array representing the image 37 | center: Tuple (x, y) for the center of the arc 38 | radius: Radius of the arc 39 | start_angle_rad: Starting angle in degrees 40 | end_angle_rad: Ending angle in degrees 41 | a: Width of the arc at the pointy end (start_angle) 42 | b: Width of the arc at the broad end (end_angle) 43 | color: Color of the arc; defaults to 255 44 | Returns: 45 | Image with the painted arc 46 | """ 47 | height, width = image.shape[:2] 48 | 49 | # Create a meshgrid 50 | y, x = np.ogrid[:height, :width] 51 | 52 | # Calculate distances and angles for each pixel 53 | dx = x - center[0] 54 | dy = y - center[1] 55 | distances = np.sqrt(dx**2 + dy**2) 56 | angles = np.arctan2(dy, dx) 57 | 58 | # Adjust angles to be in the range [0, 2π] 59 | angles = (angles + 2 * np.pi) % (2 * np.pi) 60 | start_angle_rad = (start_angle_rad + 2 * np.pi) % (2 * np.pi) 61 | end_angle_rad = (end_angle_rad + 2 * np.pi) % (2 * np.pi) 62 | 63 | # Adjust the angular mask to account for wraparound 64 | if start_angle_rad <= end_angle_rad: 65 | angle_mask = (angles >= start_angle_rad) & (angles <= end_angle_rad) 66 | else: # Wraparound case 67 | angle_mask = (angles >= start_angle_rad) | (angles <= end_angle_rad) 68 | 69 | # Calculate the angular position within the arc (0 to 1) 70 | angular_position = np.where( 71 | angle_mask, (angles - start_angle_rad) % (2 * np.pi) / ((end_angle_rad - start_angle_rad) % (2 * np.pi)), 0 72 | ) 73 | 74 | # Calculate the width at each angular position 75 | width_at_angle = start_width + (end_width - start_width) * angular_position 76 | 77 | # Create the cone shape 78 | inner_radius = radius - width_at_angle / 2 79 | outer_radius = radius + width_at_angle / 2 80 | 81 | # Create the mask for the arc 82 | arc_mask = (distances >= inner_radius) & (distances <= outer_radius) & angle_mask 83 | 84 | # Apply the mask to create a new image 85 | # result = np.copy(image) # !TBD: Maybe not required 86 | image[arc_mask] = color 87 | 88 | return image 89 | 90 | 91 | def draw_circular_gradient(width, height): 92 | """Return an image array with a circular gradient. 93 | 94 | The gradient is black (0) to white (1) along the angle from 0 to 2π. 95 | 96 | Args: 97 | width: width of the image array to generate 98 | height: height of the image array to generate 99 | 100 | Returns: 101 | gradient image array, shape=(width, height), dtype=np.float32 102 | """ 103 | # Create a grid of x, y coordinates 104 | y, x = np.ogrid[:width, :height] 105 | y = y - width // 2 106 | x = x - height // 2 107 | 108 | # Calculate the angle in radians (0 to 2π) and normalize to 0 to 1 range 109 | angle = (np.arctan2(-y, x) + 2 * np.pi) % (2 * np.pi) # Adjust range to 0 to 2π 110 | normalized_angle = angle / (2 * np.pi) # Normalize to range [0, 1] 111 | 112 | # Create gradient: black (0) to white (1) along the normalized angle 113 | gradient = normalized_angle 114 | 115 | return gradient 116 | -------------------------------------------------------------------------------- /circle_dance/game/modules/circular_sheet_stream.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import threading 3 | from abc import ABC, abstractmethod 4 | from queue import Empty, Queue 5 | 6 | from circle_dance.audio.read import callbacks, stream_reader 7 | from circle_dance.game import Game 8 | from circle_dance.game.modules import BaseModule 9 | from circle_dance.visualize import circular_sheet 10 | 11 | logger = logging.getLogger(__name__) 12 | 13 | 14 | class CircularSheetStream(BaseModule, ABC): 15 | "Base class for all notes on a circular sheet parsed from a stream." 16 | 17 | def __init__(self, threshold: float = 0.99, n_clones: int = 1): 18 | """Module that parses the OS's default input stream and animate it's notes on a circular sheet. 19 | 20 | Uses a thread to process the stream for faster processing. 21 | 22 | Args: 23 | threshold: the energy threshold for considering a note as active; between 0 and 1 24 | n_clones: number of times to clone the song to produce multiple sheets in the visualization 25 | """ 26 | assert threshold > 0 and threshold <= 1, "threshold must be between 0 and 1" 27 | assert n_clones > 0, "n_clones must be greater than 0" 28 | 29 | self.threshold = threshold 30 | self.n_clones = n_clones # !TBD: Currently not used. Implement? 31 | self.thread: threading.Thread 32 | self.close_request_event: threading.Event 33 | self.queue: Queue 34 | 35 | @abstractmethod 36 | def start_subprocess(self): 37 | "Start the thread that reads the stream and adds notes to the queue." 38 | pass 39 | 40 | def stop_subprocess(self): 41 | if self.thread.is_alive(): 42 | self.close_request_event.set() 43 | self.thread.join(timeout=2) # maximum time in seconds to wait for subprocess to terminate itself 44 | # if self.thread.exitcode is None: 45 | # self.thread.terminate() 46 | # self.thread.close() 47 | 48 | def _setup(self, g: Game): 49 | self.canvas = circular_sheet.Canvas(g.screen, n_sheets=1, note_pool=circular_sheet.DotNotePool) 50 | 51 | def _teardown(self, g: Game): 52 | self.stop_subprocess() 53 | 54 | def _pre_run(self, g: Game, clock: float): 55 | self.start_subprocess() 56 | 57 | def _post_run(self, g: Game, clock: float): 58 | pass 59 | 60 | def _update(self, g: Game, clock: float): 61 | note: float 62 | onset: float 63 | conclusion: float 64 | energy: float 65 | 66 | # read all pending notes from the queue and add to canvas 67 | while not self.queue.empty(): 68 | try: 69 | note, onset, conclusion, energy = self.queue.get_nowait() 70 | self.canvas.add_note(0, int(note), onset, conclusion, energy) 71 | except Empty: 72 | pass 73 | 74 | # draw canvas 75 | self.canvas.draw(clock) 76 | 77 | def _should_terminate(self, g: Game, clock: float) -> bool: 78 | if not self.thread.is_alive(): 79 | logger.warn("notes_producer subprocess died; signaling game to terminate") 80 | return True 81 | return False 82 | 83 | 84 | class DotNotesOnCircularSheetStream(CircularSheetStream): 85 | 86 | def start_subprocess(self): 87 | self.queue = Queue() # queue for notes 88 | self.close_request_event = threading.Event() 89 | self.thread = threading.Thread( 90 | target=stream_reader, 91 | args=(callbacks.extract_node_onsets_callback, self.queue, self.close_request_event, 5, 20), 92 | # buffer_replenish_multiplier, buffer_carryover_multiplier 93 | ) 94 | self.thread.start() 95 | 96 | 97 | class SimpleArcNotesOnCircularSheetStream(CircularSheetStream): 98 | 99 | def start_subprocess(self): 100 | self.queue = Queue() # queue for notes 101 | self.close_request_event = threading.Event() 102 | self.thread = threading.Thread( 103 | target=stream_reader, 104 | args=(callbacks.extract_note_durations_callback, self.queue, self.close_request_event, 1, 20), 105 | # buffer_replenish_multiplier, buffer_carryover_multiplier 106 | ) 107 | self.thread.start() 108 | 109 | def _setup(self, g: Game): 110 | self.canvas = circular_sheet.Canvas(g.screen, n_sheets=1, note_pool=circular_sheet.SimpleArcNotePool) 111 | 112 | 113 | class ArcNotesOnCircularSheetStream(CircularSheetStream): 114 | 115 | def _setup(self, g: Game): 116 | self.canvas = circular_sheet.Canvas(g.screen, n_sheets=1, note_pool=circular_sheet.ArcNotePool) 117 | -------------------------------------------------------------------------------- /circle_dance/audio/read/stream.py: -------------------------------------------------------------------------------- 1 | # stream reader 2 | 3 | import logging 4 | import queue 5 | import threading 6 | from queue import Empty, Full 7 | from typing import Callable, TypeAlias 8 | 9 | import numpy as np 10 | import numpy.typing as npt 11 | import pyaudio 12 | 13 | logger = logging.getLogger(__name__) 14 | 15 | 16 | # !NOTE: 17 | # When the processing of an audio buffer has a runtime > buffer_replenish_multiplier * CHUNK / RATE, then the notes will slowly get more and more delayed 18 | # potential solution: discard older notes, always empty audio buffer until no more to get 19 | # !NOTE: 20 | # buffer_replenish_multiplier * CHUNK / RATE is minimum delay between displays - should be <= 0.02s to be perceived as real time 21 | # !NOTE: 22 | # Doubling the RATE effectively halves the CHUNK 23 | 24 | # e.g. def process_buffer(buffer, sr, stream_clock, carryover_samples, carryover_time_sec) -> list 25 | T_CALLBACK_PROCESS_BUFFER: TypeAlias = Callable[ 26 | [npt.NDArray[np.int16], float, float, int, float], npt.NDArray[np.float32] 27 | ] 28 | 29 | # Main stream parameters 30 | CHUNK = 1024 # 1024 Number of frames per buffer 31 | FORMAT = pyaudio.paInt16 # Format of the audio samples 32 | CHANNELS = 1 # Number of channels (1 for mono, 2 for stereo) 33 | RATE = 44100 # 44100 # 22050 # Sample rate (samples per second) 34 | 35 | 36 | def stream_reader( 37 | process_buffer_callback: T_CALLBACK_PROCESS_BUFFER, 38 | queue: queue.Queue, 39 | close_request_event: threading.Event, 40 | buffer_replenish_multiplier: int, 41 | buffer_carryover_multiplier: int, 42 | ): 43 | """Producer that produces notes from an audio stream. Meant to be run with multithreading. 44 | 45 | Note: 46 | Does not run well with multiprocessing. Causes input buffer overflow. 47 | 48 | Args: 49 | process_buffer_callback: function to call to process each buffer 50 | queue: the queue to put the notes into 51 | close_request_event: closes itself once this event has been triggered 52 | buffer_replenish_multiplier: wait until we obtained this times CHUNK of new audio data until we process the buffer 53 | buffer_carryover_multiplier: carry over this times CHUNK of audio data from last call to the next call 54 | """ 55 | p = pyaudio.PyAudio() 56 | stream = p.open( 57 | format=FORMAT, 58 | channels=CHANNELS, 59 | rate=RATE, 60 | input=True, 61 | frames_per_buffer=CHUNK, 62 | ) 63 | 64 | stream_clock = 0.0 # position in stream; and position in buffer after carryover samples; in seconds 65 | buffer = np.array([], dtype=np.int16) 66 | 67 | # read steam, process audio data, and write note to queue 68 | try: 69 | while not close_request_event.is_set(): 70 | carryover_offset_samples = len(buffer) 71 | carryover_offset_sec = carryover_offset_samples / RATE 72 | # print("sp: carryover_offset_sec", carryover_offset_sec) 73 | 74 | # fill up buffer 75 | while len(buffer) - carryover_offset_samples < CHUNK * buffer_replenish_multiplier: 76 | # Read a chunk of data from the stream 77 | data = stream.read(CHUNK) 78 | # Convert the byte data to numpy array 79 | audio_chunk = np.frombuffer(data, dtype=np.int16) 80 | # Append the new chunk to the buffer 81 | buffer = np.append(buffer, audio_chunk) 82 | 83 | # callback buffer processor 84 | items = process_buffer_callback( 85 | buffer, 86 | RATE, 87 | stream_clock, 88 | carryover_offset_samples, 89 | carryover_offset_sec, 90 | ) 91 | 92 | # put items into queue, keeping newest items 93 | for item in items: 94 | if queue.full(): # make one attempt at removing the oldest note in the queue if full 95 | try: 96 | logger.warn("queue full, trying to discard oldest item") 97 | queue.get_nowait() 98 | except Empty: 99 | pass 100 | try: # try, discard if didn't work 101 | queue.put_nowait(item) 102 | except Full: 103 | logger.warn("discarded item due to full queue") 104 | pass 105 | 106 | # update stream clock 107 | stream_clock += len(buffer) / RATE - carryover_offset_sec # subtract time of carryover samples 108 | 109 | # keep something at the end of the buffer for better continuity 110 | buffer = buffer[-CHUNK * buffer_carryover_multiplier :] 111 | finally: 112 | stream.stop_stream() 113 | stream.close() 114 | p.terminate() 115 | -------------------------------------------------------------------------------- /circle_dance/game/game.py: -------------------------------------------------------------------------------- 1 | # principal game runner 2 | 3 | import functools 4 | import time 5 | from typing import Callable, TypeAlias 6 | 7 | import pygame 8 | 9 | 10 | class Game: 11 | 12 | # base types 13 | __T_CALLBACK_WO_CLOCK: TypeAlias = Callable[["Game"], None] # note: forward reference 14 | __T_CALLBACK_W_CLOCK: TypeAlias = Callable[["Game", float], None] 15 | 16 | # callback types 17 | T_CALLBACK_SETUP: TypeAlias = __T_CALLBACK_WO_CLOCK 18 | T_CALLBACK_TEARDOWN: TypeAlias = __T_CALLBACK_WO_CLOCK 19 | T_CALLBACK_PRE_RUN: TypeAlias = __T_CALLBACK_W_CLOCK 20 | T_CALLBACK_POST_RUN: TypeAlias = __T_CALLBACK_W_CLOCK 21 | T_CALLBACK_UPDATE: TypeAlias = __T_CALLBACK_W_CLOCK 22 | T_CALLBACK_SHOULD_TERMINATE: TypeAlias = Callable[["Game", float], bool] 23 | T_CALLBACK_KEYDOWN: TypeAlias = __T_CALLBACK_WO_CLOCK 24 | 25 | def __init__(self) -> None: 26 | """Game implementation. 27 | 28 | Takes care of initializing pygame, prepares the screen, maintains the synchronization clock, and provides a 29 | callback interface for modules to register to. 30 | 31 | Also takes care of teardown and all global functionality, such as processing quit commands. 32 | 33 | !TBD: 34 | - add some parameters (e.g. fullscreen, window size, window title) 35 | - add some logging 36 | - add some way to register event callbacks (e.g. key press, mouse click) 37 | - add some error handling (quit game gracefully) 38 | - callbacks registration also need to provide module name for better debug logging 39 | - print debug info on click duration, e.g. every 10 clicks the average or such 40 | """ 41 | self.__callbacks_setup: list[Game.T_CALLBACK_SETUP] = [] 42 | self.__callbacks_teardown: list[Game.T_CALLBACK_TEARDOWN] = [] 43 | self.__callbacks_pre_run: list[Game.T_CALLBACK_PRE_RUN] = [] 44 | self.__callbacks_post_run: list[Game.T_CALLBACK_POST_RUN] = [] 45 | self.__callbacks_update: list[Game.T_CALLBACK_UPDATE] = [] 46 | self.__callbacks_should_terminate: list[Game.T_CALLBACK_SHOULD_TERMINATE] = [] 47 | self.__callbacks_keydown: dict[int, Game.T_CALLBACK_KEYDOWN] = {} 48 | 49 | def run(self) -> None: 50 | "Run the game." 51 | # setup 52 | self._setup() 53 | [c(self) for c in self.__callbacks_setup] 54 | 55 | # Animation loop 56 | start_time = time.time() 57 | clock = 0.0 58 | running = True 59 | 60 | # pre-run callbacks 61 | [c(self, clock) for c in self.__callbacks_pre_run] 62 | 63 | while running: 64 | # exit on ESC and pygame.QUIT 65 | for event in pygame.event.get(): 66 | if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE): 67 | running = False 68 | elif event.type == pygame.KEYDOWN and event.key in self.__callbacks_keydown: 69 | self.__callbacks_keydown[event.key](self) # handle keydown callbacks 70 | 71 | # update clock 72 | clock = time.time() - start_time 73 | 74 | # update by calling update on each module 75 | # mainly used to update the screen 76 | [c(self, clock) for c in self.__callbacks_update] 77 | 78 | pygame.display.flip() 79 | 80 | # check if termination desire signaled by any module 81 | if functools.reduce(lambda a, b: a or b, [c(self, clock) for c in self.__callbacks_should_terminate]): 82 | running = False 83 | 84 | # post-run callbacks 85 | clock = time.time() - start_time 86 | [c(self, clock) for c in self.__callbacks_post_run] 87 | 88 | # teardown 89 | [c(self) for c in self.__callbacks_teardown] 90 | self._teardown() 91 | 92 | def register_setup_callback(self, callback: T_CALLBACK_SETUP) -> None: 93 | self.__callbacks_setup.append(callback) 94 | 95 | def register_teardown_callback(self, callback: T_CALLBACK_TEARDOWN) -> None: 96 | self.__callbacks_teardown.append(callback) 97 | 98 | def register_pre_run_callback(self, callback: T_CALLBACK_PRE_RUN) -> None: 99 | self.__callbacks_pre_run.append(callback) 100 | 101 | def register_post_run_callback(self, callback: T_CALLBACK_POST_RUN) -> None: 102 | self.__callbacks_post_run.append(callback) 103 | 104 | def register_update_callback(self, callback: T_CALLBACK_UPDATE) -> None: 105 | self.__callbacks_update.append(callback) 106 | 107 | def register_should_terminate_callback(self, callback: T_CALLBACK_SHOULD_TERMINATE) -> None: 108 | self.__callbacks_should_terminate.append(callback) 109 | 110 | def register_keydown_callback(self, key: int, callback: T_CALLBACK_KEYDOWN) -> None: 111 | self.__callbacks_keydown[key] = callback 112 | 113 | def _setup(self) -> None: 114 | "Game setup, before the clock starts." 115 | pygame.init() 116 | 117 | # get screen resolution 118 | info = pygame.display.Info() 119 | screen_width, screen_height = info.current_w, info.current_h 120 | 121 | # Screen setup 122 | width, height = screen_width, screen_height 123 | screen = pygame.display.set_mode((width, height), pygame.FULLSCREEN) 124 | pygame.display.set_caption("Circular Music Sheet Animation") 125 | 126 | self.screen = screen 127 | 128 | def _teardown(self) -> None: 129 | "Game teardown, after the clock stops." 130 | pygame.quit() 131 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/note_pool.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: note pools 2 | # manages the notes on a sheet and the adding of new notes 3 | 4 | import math 5 | from abc import ABC, abstractmethod 6 | 7 | import numpy as np 8 | import numpy.typing as npt 9 | import pygame 10 | from scipy import ndimage 11 | 12 | from circle_dance.visualize import Drawable 13 | from circle_dance.visualize.circular_sheet import ( 14 | ArcNote, 15 | ArcNote_Legacy, 16 | DotNote, 17 | Note, 18 | SimpleArcNote, 19 | config, 20 | utils, 21 | ) 22 | from circle_dance.visualize.draw import draw_circular_gradient 23 | from circle_dance.visualize.types import T_COLOR 24 | 25 | 26 | class NotePool(Drawable, ABC): 27 | 28 | def __init__(self, surface: pygame.Surface, note_base_radius: int, note_size: int, note_color: T_COLOR): 29 | """Note pool base class. 30 | 31 | Manages the notes and allows to add more notes. 32 | 33 | Args: 34 | surface: the surface the notes are drawn upon 35 | note_base_radius: the base radius of the notes 36 | the first note of the scale will be placed on this radius, all other accordingly 37 | note_size: the base size of the notes 38 | note_color: the color of the notes 39 | """ 40 | super().__init__(surface) 41 | 42 | self.note_size = note_size # node_size = self.dist_between_sheet_lines // 2 # two notes per line, as half-tones are possible 43 | self.note_color = note_color 44 | self.note_base_radius = note_base_radius # self.radius_outer 45 | 46 | self.notes: list[Note] = [] 47 | 48 | @abstractmethod 49 | def add_note(self, note: int, onset: float, conclusion: float, energy: float): 50 | """Add a note to the note pool. 51 | 52 | This method takes the note details as returned by a method in `circle_dance.audio.process` and creates the 53 | appropriate note. The type of note added depends on the actual note pool implementation. 54 | 55 | Args: 56 | note: note id, aka a number between 0 and 12 57 | onset: onset time of the note, in seconds 58 | conclusion: conclusion time of the note, in seconds 59 | energy: chroma energy of the note, a value between 0 and 1 60 | """ 61 | pass 62 | 63 | def draw(self, t: float) -> None: 64 | self._remove_dead_notes(t) 65 | for note in self.notes: 66 | note.draw(t) 67 | 68 | def _remove_dead_notes(self, t: float): 69 | self.notes = [n for n in self.notes if n.is_alive(t)] 70 | 71 | def _get_note_radius(self, note: int): 72 | "Compute the appropriate radius location of the note." 73 | return ( 74 | self.note_base_radius - (11 - note) * self.note_size 75 | ) # first note is placed on radius, then half-line steps; reversed order to get deeper notes on the inner radius 76 | 77 | 78 | class DotNotePool(NotePool): 79 | 80 | def add_note(self, note: int, onset: float, conclusion: float, energy: float): 81 | # compute note location from onset and base radius 82 | radius = self._get_note_radius(note) 83 | angle = utils.get_angle_at_time(onset) # note position of circle according to it's onset 84 | x = self.surface.get_width() // 2 + radius * math.cos(angle) 85 | y = self.surface.get_height() // 2 + radius * math.sin(angle) 86 | 87 | self.notes.append( 88 | DotNote( 89 | self.surface, 90 | x, 91 | y, 92 | self.note_size, 93 | self.note_color, 94 | onset, 95 | config.rotation_period - 1, 96 | ) 97 | ) 98 | 99 | 100 | class ArcNotePool(NotePool): 101 | 102 | def __init__(self, surface: pygame.Surface, note_base_radius: int, note_size: int, note_color: T_COLOR): 103 | super().__init__(surface, note_base_radius, note_size, note_color) 104 | 105 | # prepare an pixel-wise alpha enabled surface for the notes to be drawn on 106 | self.surface_notes = pygame.Surface((self.surface.get_width(), self.surface.get_height()), pygame.SRCALPHA) 107 | self.arr = np.zeros(self.surface_notes.get_size(), dtype=np.bool) 108 | 109 | def add_note(self, note: int, onset: float, conclusion: float, energy: float): 110 | # compute note radius position from base radius 111 | radius = self._get_note_radius(note) 112 | 113 | # if there is already a note on the same sheet line (same radius position) and with overlapping [onset, conclusion] time 114 | # then update that note's conclusion time 115 | for n in self.notes: 116 | assert isinstance(n, ArcNote) 117 | if n.radius == radius and onset <= n.conclusion: 118 | n.conclusion = conclusion 119 | return 120 | 121 | # otherwise add a new ArcNote 122 | self.notes.append( 123 | ArcNote( 124 | self.surface_notes, radius, 1, self.note_size, onset, conclusion, config.rotation_period - 1, self.arr 125 | ) 126 | ) 127 | 128 | def draw(self, t: float) -> None: 129 | self.surface_notes.fill((0, 0, 0, 0)) # clear note surface; make transparent 130 | self.arr.fill(0) # clear array 131 | print("#note:", len(self.notes)) 132 | super().draw(t) # let the notes draw their b/w arcs 133 | 134 | # get pixel values from surface (they denote the locations of the arc pixels) 135 | # arc_pixels = pygame.surfarray.array2d(self.surface_notes).astype(np.bool) 136 | arc_pixels = self.arr 137 | 138 | print("sum:", arc_pixels.sum()) 139 | 140 | # create color image (3 channels, no alpha) 141 | color_channels = np.dstack( 142 | [ 143 | arc_pixels * self.note_color[0], 144 | arc_pixels * self.note_color[1], 145 | arc_pixels * self.note_color[2], 146 | ] 147 | ) 148 | 149 | # write color values to note surface 150 | pygame.surfarray.blit_array(self.surface_notes, color_channels) 151 | 152 | # write alpha channel to note surface 153 | # Note: not save in var, as saving in var would acquire surface lock; can only be released with del var 154 | pygame.surfarray.pixels_alpha(self.surface_notes)[:] = ArcNotePool._make_alpha_channel(t, arc_pixels) 155 | 156 | self.surface.blit(self.surface_notes, (0, 0)) # blit note image onto the main pool surface 157 | 158 | @staticmethod 159 | def _make_alpha_channel(t: float, arc_pixels: npt.NDArray[np.bool]) -> npt.NDArray[np.uint8]: 160 | """Create the alpha channel for the current time. 161 | 162 | The channel will have a circular gradient alpha where there are note pixels, starting at the angle of `t`. 163 | The rest of the channel is set to full transparency. 164 | 165 | Args: 166 | t: current time in seconds 167 | arc_pixels: boolean array denoting the pixels of the arc 168 | """ 169 | t_rad = utils.get_angle_at_time(t) 170 | lt_factor = ( 171 | config.rotation_period - 1 172 | ) / config.rotation_period - 1 # lifetime as factor of total rotation period 173 | alpha_channel = draw_circular_gradient(*arc_pixels.shape) 174 | alpha_channel = np.clip( 175 | alpha_channel / lt_factor, 0, 1 176 | ) # limit gradient's maximum transparency to factor of complete circle 177 | alpha_channel = ndimage.rotate( 178 | alpha_channel, -np.rad2deg(t_rad), reshape=False, mode="nearest" 179 | ) # rotate transparency gradient to current time's location 180 | alpha_channel = ((1 - alpha_channel) * 255).astype(np.uint8) 181 | alpha_channel[~arc_pixels] = 0 # set alpha to max transparency where there is no arc 182 | 183 | return alpha_channel 184 | 185 | 186 | class SimpleArcNotePool(NotePool): 187 | 188 | def add_note(self, note: int, onset: float, conclusion: float, energy: float): 189 | # compute note radius position from base radius 190 | radius = self._get_note_radius(note) 191 | 192 | # if there is already a note on the same sheet line (same radius position) and with overlapping [onset, conclusion] time 193 | # then update that note's conclusion time 194 | for n in self.notes: 195 | assert isinstance(n, SimpleArcNote) 196 | if n.radius == radius and onset <= n.conclusion: 197 | n.conclusion = conclusion 198 | return 199 | 200 | # otherwise add a new ArcNote 201 | self.notes.append( 202 | SimpleArcNote( 203 | self.surface, 204 | radius, 205 | self.note_size, 206 | self.note_color, 207 | onset, 208 | conclusion, 209 | config.rotation_period - 1, 210 | ) 211 | ) 212 | 213 | 214 | class ArcNotePool_Legacy(NotePool): 215 | 216 | def add_note(self, note: int, onset: float, conclusion: float, energy: float): 217 | # compute note radius position from base radius 218 | radius = self._get_note_radius(note) 219 | 220 | # if there is already a note on the same sheet line (same radius position) and with overlapping [onset, conclusion] time 221 | # then update that note's conclusion time 222 | for n in self.notes: 223 | assert isinstance(n, ArcNote) 224 | if n.radius == radius and onset <= n.conclusion: 225 | n.conclusion = conclusion 226 | return 227 | 228 | # otherwise add a new ArcNote 229 | self.notes.append( 230 | ArcNote_Legacy( 231 | self.surface, 232 | radius, 233 | self.note_size, 234 | self.note_color, 235 | onset, 236 | conclusion, 237 | config.rotation_period - 1, 238 | ) 239 | ) 240 | -------------------------------------------------------------------------------- /circle_dance/visualize/circular_sheet/notes.py: -------------------------------------------------------------------------------- 1 | # circular sheet visualization: notes 2 | 3 | import logging 4 | import math 5 | from abc import ABC, abstractmethod 6 | 7 | import numpy as np 8 | import pygame 9 | 10 | from circle_dance.visualize import Drawable 11 | from circle_dance.visualize.circular_sheet import utils 12 | from circle_dance.visualize.draw import draw_circle_alpha, draw_cone_arc 13 | from circle_dance.visualize.types import T_COLOR 14 | 15 | logger = logging.getLogger(__name__) 16 | 17 | 18 | class Note(Drawable, ABC): 19 | 20 | @abstractmethod 21 | def is_alive(self, t: float) -> bool: 22 | """Check if the note is still alive. 23 | 24 | Args: 25 | t: current time in seconds 26 | 27 | Returns: 28 | whether or not the note has reached the end of it's lifetime 29 | """ 30 | pass 31 | 32 | 33 | class DotNote(Note): 34 | def __init__( 35 | self, surface: pygame.Surface, x: float, y: float, size: int, color: T_COLOR, onset: float, lifetime: float 36 | ): 37 | """Define a note on a surfaced visualized as a dot/circle. 38 | 39 | Args: 40 | screen: surface to draw on 41 | x: x-coordinate of the note 42 | y: y-coordinate of the note 43 | size: size of the note 44 | color: color of the note 45 | onset: time when the note is played; seconds 46 | lifetime: time the note should be displayed for; seconds 47 | """ 48 | super().__init__(surface) 49 | 50 | self.x = x 51 | self.y = y 52 | self.size = size 53 | self.color = color 54 | self.onset = onset 55 | self.lifetime = lifetime 56 | 57 | def is_alive(self, t: float) -> bool: 58 | return self.onset + self.lifetime >= t 59 | 60 | def draw(self, t: float) -> None: 61 | """Draw a circle representing the note. 62 | 63 | Args: 64 | t: current time in seconds 65 | """ 66 | if t >= self.onset and t <= self.onset + self.lifetime: 67 | strength = 1 - (t - self.onset) / self.lifetime 68 | self.__draw_note(strength) 69 | 70 | def __draw_note(self, strength: float) -> None: 71 | """Draw a circle representing the note. 72 | 73 | Args: 74 | strength: strength of the note, used to determine its transparency and size 75 | """ 76 | alpha = int(255 * strength) 77 | color = self.color[:3] + (alpha,) 78 | size = self.size * ((1 - strength) * 10 + 1) 79 | draw_circle_alpha(self.surface, color, (self.x, self.y), size) 80 | # pygame.draw.circle(self.surface, color, (self.x, self.y), size) 81 | 82 | 83 | class ArcNote(Note): 84 | def __init__( 85 | self, 86 | surface: pygame.Surface, 87 | radius: float, 88 | size_min: int, 89 | size_max: int, 90 | onset: float, 91 | conclusion: float, 92 | lifetime: float, 93 | arr, 94 | ): 95 | """Define a note on a surface visualized as a duration arc. 96 | 97 | Args: 98 | screen: surface to draw on 99 | radius: radius of the note arc 100 | size_min: minimum width of arc (at pointy end) 101 | size_max: maximum width of arc (at blunt end, at end of it's lifetimes) 102 | color: color of the note 103 | onset: time when the note is played; seconds 104 | conclusion: time when the note is no longer heard; seconds 105 | lifetime: time the note should be displayed for; seconds 106 | """ 107 | super().__init__(surface) 108 | 109 | self.radius = radius 110 | self.size_min = size_min 111 | self.size_max = size_max 112 | self.onset = onset 113 | self.conclusion = conclusion 114 | self.lifetime = lifetime 115 | 116 | self.arr = arr 117 | 118 | self.onset_angle = utils.get_angle_at_time(self.onset) 119 | self.surface_width = self.surface.get_width() 120 | self.surface_height = self.surface.get_height() 121 | self.center = self.surface_height // 2, self.surface_width // 2 122 | 123 | def is_alive(self, t: float) -> bool: 124 | return t - self.conclusion < self.lifetime 125 | 126 | def draw(self, t: float) -> None: 127 | """Draw an arc line representing a note with duration. 128 | 129 | Args: 130 | t: current time in seconds 131 | """ 132 | if t >= self.onset and t - self.conclusion < self.lifetime: 133 | self.__draw_note(t) 134 | 135 | def __draw_note(self, t: float): 136 | """Draw a cone-shaped arc with gradual transparency by drawing multiple dots along an arc line. 137 | 138 | Args: 139 | t: current time in seconds 140 | """ 141 | assert t > self.onset, "arc's onset lies in the future" 142 | assert t - self.conclusion < self.lifetime, "arc's lifetime has expired and cannot be drawn" 143 | assert self.conclusion > self.onset, "arc's length is zero or less" 144 | 145 | # derived parameters 146 | t_arc_start = min(t, self.conclusion) 147 | t_arc_start_rad = utils.get_angle_at_time(t_arc_start) 148 | t_arc_end = max(self.onset, t - self.lifetime) 149 | t_arc_end_rad = utils.get_angle_at_time(t_arc_end) 150 | 151 | width_arc_start = (t - t_arc_start) / self.lifetime * (self.size_max - self.size_min) + self.size_min 152 | width_arc_end = (t - t_arc_end) / self.lifetime * (self.size_max - self.size_min) + self.size_min 153 | 154 | print("start-end", t_arc_start, t_arc_end) 155 | print("arr.shape", self.arr.shape) 156 | print("radius", self.radius) 157 | print("center", self.center) 158 | 159 | # construct cone shape arc 160 | # surface_arr = pygame.surfarray.array3d(self.surface) 161 | return draw_cone_arc( 162 | self.arr, 163 | self.center, 164 | self.radius, 165 | t_arc_end_rad, 166 | t_arc_start_rad, # paints from wide end clock-wise 167 | width_arc_end, 168 | width_arc_start, 169 | ) 170 | # del surface_arr 171 | 172 | 173 | class SimpleArcNote(Note): 174 | def __init__( 175 | self, 176 | surface: pygame.Surface, 177 | radius: float, 178 | size: int, 179 | color: T_COLOR, 180 | onset: float, 181 | conclusion: float, 182 | lifetime: float, 183 | ): 184 | """Define a note on a surface visualized as a duration arc. 185 | 186 | Args: 187 | screen: surface to draw on 188 | radius: radius of the note arc 189 | size: size of the note 190 | color: color of the note 191 | onset: time when the note is played; seconds 192 | conclusion: time when the note is no longer heard; seconds 193 | lifetime: time the note should be displayed for; seconds 194 | """ 195 | super().__init__(surface) 196 | 197 | self.radius = radius 198 | self.size = size 199 | self.color = color 200 | self.onset = onset 201 | self.conclusion = conclusion 202 | self.lifetime = lifetime 203 | 204 | self.onset_angle = utils.get_angle_at_time(self.onset) 205 | 206 | def is_alive(self, t: float) -> bool: 207 | return self.onset + self.lifetime >= t 208 | 209 | def draw(self, t: float) -> None: 210 | """Draw an arc line representing a note with duration. 211 | 212 | Args: 213 | t: current time in seconds 214 | """ 215 | if t >= self.onset and t <= self.onset + self.lifetime: 216 | self.__draw_note(t) 217 | 218 | def __draw_note(self, t: float): 219 | """Draw a simple arc line. 220 | 221 | Args: 222 | t: current time in seconds 223 | """ 224 | assert t > self.onset 225 | assert t - self.onset <= self.lifetime 226 | 227 | # derived parameters 228 | t_arc_start = min(t, self.conclusion) 229 | t_arc_start_rad = utils.get_angle_at_time(t_arc_start) 230 | t_arc_end = max(self.onset, t - self.lifetime) 231 | t_arc_end_rad = utils.get_angle_at_time(t_arc_end) 232 | 233 | w, h = self.surface.get_size() 234 | radius_corrected = self.radius + self.size // 2 # arc paints width only inwards 235 | rect = pygame.Rect( 236 | w // 2 - radius_corrected, h // 2 - radius_corrected, 2 * radius_corrected, 2 * radius_corrected 237 | ) 238 | # pygame.draw.arc(self.surface, self.color, rect, -np.deg2rad(45), np.deg2rad(0), self.size) 239 | pygame.draw.arc( 240 | self.surface, self.color, rect, 2 * np.pi - t_arc_start_rad, 2 * np.pi - t_arc_end_rad, self.size 241 | ) 242 | 243 | 244 | class ArcNote_Legacy(Note): 245 | def __init__( 246 | self, 247 | surface: pygame.Surface, 248 | radius: float, 249 | size: int, 250 | color: T_COLOR, 251 | onset: float, 252 | conclusion: float, 253 | lifetime: float, 254 | ): 255 | """Define a note on a surface visualized as a duration arc. 256 | 257 | Args: 258 | screen: surface to draw on 259 | radius: radius of the note arc 260 | size: size of the note 261 | color: color of the note 262 | onset: time when the note is played; seconds 263 | conclusion: time when the note is no longer heard; seconds 264 | lifetime: time the note should be displayed for; seconds 265 | """ 266 | super().__init__(surface) 267 | 268 | self.radius = radius 269 | self.size = size 270 | self.color = color 271 | self.onset = onset 272 | self.conclusion = conclusion 273 | self.lifetime = lifetime 274 | 275 | self.onset_angle = utils.get_angle_at_time(self.onset) 276 | 277 | def is_alive(self, t: float) -> bool: 278 | return self.onset + self.lifetime >= t 279 | 280 | def draw(self, t: float) -> None: 281 | """Draw an arc line representing a note with duration. 282 | 283 | Args: 284 | t: current time in seconds 285 | """ 286 | if t >= self.onset and t <= self.onset + self.lifetime: 287 | self.__draw_note(t, min_width=max(3, self.size // 5), max_width=self.size * 3) 288 | 289 | def __draw_note(self, t: float, min_width: int, max_width: int, max_dots: int = 1000): 290 | """Draw a cone-shaped arc with gradual transparency by drawing multiple dots along an arc line. 291 | 292 | Args: 293 | t: current time in seconds 294 | min_width: width of the arc at it's pointy end 295 | max_width: width of the arc at it's blunt end 296 | max_dots: maximum number of dots to utilize to simulate the arc; default 1000 297 | """ 298 | assert t > self.onset 299 | assert t - self.onset <= self.lifetime 300 | 301 | # start & end times of note arc @ current time t, clockwise 302 | t_start = self.onset 303 | t_end = min(t, self.conclusion) 304 | 305 | # visualization strength at start & end of note arc 306 | # depends on location in range [t - lifetime, t] 307 | # the more distant from t a location, the less visualization strength 308 | str_start = 1 - max(0, t - t_start) / self.lifetime 309 | str_end = 1 - max(0, t - t_end) / self.lifetime 310 | 311 | alpha_start = 255 * str_start 312 | alpha_end = 255 * str_end 313 | 314 | width_start = min_width + (1 - str_start) * (max_width - min_width) 315 | width_end = min_width + (1 - str_end) * (max_width - min_width) 316 | 317 | # number of dots to actually draw depends on note arc length @ t 318 | # the maximum number of dots are only used when arc length maximum, aka equal lifetime 319 | n_dots = max(1, int((t_end - t_start) / self.lifetime * max_dots)) 320 | 321 | # loop vars 322 | width_delta = (width_end - width_start) / n_dots 323 | alpha_delta = (alpha_end - alpha_start) / n_dots 324 | 325 | dot_id = 0 326 | for dot_t in np.linspace(t_start, t_end, n_dots): 327 | x = int( 328 | self.surface.get_width() // 2 329 | + self.radius * math.sin(utils.get_angle_at_time(dot_t) + math.radians(90)) 330 | ) 331 | y = int( 332 | self.surface.get_height() // 2 333 | - self.radius * math.cos(utils.get_angle_at_time(dot_t) + math.radians(90)) 334 | ) 335 | 336 | dot_color = self.color[:3] + (int(alpha_start + dot_id * alpha_delta),) 337 | dot_width = int(width_start + dot_id * width_delta) 338 | 339 | # pygame.draw.circle(self.surface, dot_color, (x, y), dot_width) 340 | draw_circle_alpha(self.surface, dot_color, (x, y), dot_width) 341 | 342 | dot_id += 1 343 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------