├── tests ├── __init__.py └── test_audio_degradation_toolbox.py ├── audio_degradation_toolbox ├── __init__.py ├── __version__.py ├── playback.py ├── audio.py ├── cli.py ├── core.py └── degradations.py ├── requirements.txt ├── .gitattributes ├── presets ├── strong_mp3.json ├── dopbandpass.json ├── live_recording.json ├── smartphone_playback.json ├── radio_broadcast.json ├── vinyl_recording.json └── smartphone_recording.json ├── samples ├── IR_GreatHall.wav ├── restaurant08.wav ├── IR_VinylPlayer1960.wav ├── Noise_OldDustyRecording.wav ├── IR_GoogleNexusOneFrontMic.wav ├── IR_GoogleNexusOneFrontSpeaker.wav └── Viola.arco.ff.sulC.E3.stereo.aiff ├── .gitignore ├── setup.py ├── README.md └── LICENSE /tests/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/__version__.py: -------------------------------------------------------------------------------- 1 | __version__ = "0.0.1" 2 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | acoustics 2 | numpy 3 | pydub 4 | scipy 5 | librosa 6 | pysndfx 7 | numba 8 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | *.wav filter=lfs diff=lfs merge=lfs -text 2 | *.aiff filter=lfs diff=lfs merge=lfs -text 3 | -------------------------------------------------------------------------------- /presets/strong_mp3.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "mp3", 4 | "bitrate": 32 5 | }, 6 | { 7 | "name": "normalize" 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /samples/IR_GreatHall.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:77493d64f1260c39e905dad8071aeb8b6486f69d4a13ca5f4f7241482a176dfd 3 | size 192078 4 | -------------------------------------------------------------------------------- /samples/restaurant08.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:ada1f0cae6349aa1ca62e0bbc96b706cf136273dc2cacafd82b23524f4f97f45 3 | size 2646044 4 | -------------------------------------------------------------------------------- /samples/IR_VinylPlayer1960.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:2a84e2d8b99889a3b808dd19b0179bea8e5201a5f7daf968a8efc0bd9db72d55 3 | size 1050 4 | -------------------------------------------------------------------------------- /samples/Noise_OldDustyRecording.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:7ce53022adde457e32ba9a2d839ec00664e274afd0bd705fbc5eebee9d4f1ab9 3 | size 960078 4 | -------------------------------------------------------------------------------- /samples/IR_GoogleNexusOneFrontMic.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:a5582971dfe2c13a9ff0119711bae245b2bae503a5f8ecf3ab53fc00ad1246a6 3 | size 48078 4 | -------------------------------------------------------------------------------- /samples/IR_GoogleNexusOneFrontSpeaker.wav: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:e9406b20731d6991681f188897083c7c3a8d7239562673dd29f91bd8bf4d741b 3 | size 7698 4 | -------------------------------------------------------------------------------- /samples/Viola.arco.ff.sulC.E3.stereo.aiff: -------------------------------------------------------------------------------- 1 | version https://git-lfs.github.com/spec/v1 2 | oid sha256:700846a8db306ccf18508bb863790e38038ec3baf216ccbb4205b4e528ed9a2a 3 | size 970078 4 | -------------------------------------------------------------------------------- /presets/dopbandpass.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "low_pass", 4 | "cutoff": 5000 5 | }, 6 | { 7 | "name": "high_pass", 8 | "cutoff": 133.33 9 | }, 10 | { 11 | "name": "normalization" 12 | } 13 | ] 14 | -------------------------------------------------------------------------------- /presets/live_recording.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "impulse_response", 4 | "path": "./samples/IR_GreatHall.wav" 5 | }, 6 | { 7 | "name": "noise", 8 | "color": "pink", 9 | "snr": 40 10 | }, 11 | { 12 | "name": "normalize" 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /presets/smartphone_playback.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "impulse_response", 4 | "path": "./samples/IR_GoogleNexusOneFrontSpeaker.wav" 5 | }, 6 | { 7 | "name": "noise", 8 | "color": "pink", 9 | "snr": 40 10 | }, 11 | { 12 | "name": "normalize" 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/playback.py: -------------------------------------------------------------------------------- 1 | from tempfile import NamedTemporaryFile 2 | import subprocess 3 | 4 | 5 | def playback_shim(audio): 6 | with NamedTemporaryFile() as audio_f: 7 | audio.export(audio_f.name) 8 | subprocess.check_output("mpv {0}".format(audio_f.name), shell=True) 9 | -------------------------------------------------------------------------------- /presets/radio_broadcast.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "dynamic_range_compression", 4 | "threshold": -40, 5 | "ratio": 1.7, 6 | "attack": 0.2, 7 | "release": 0.2 8 | }, 9 | { 10 | "name": "delay", 11 | "samples": 9600 12 | }, 13 | { 14 | "name": "speedup", 15 | "speed": 1.02 16 | }, 17 | { 18 | "name": "normalize" 19 | } 20 | ] 21 | -------------------------------------------------------------------------------- /presets/vinyl_recording.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "impulse_response", 4 | "path": "./samples/IR_VinylPlayer1960.wav" 5 | }, 6 | { 7 | "name": "mix", 8 | "path": "./samples/Noise_OldDustyRecording.wav", 9 | "snr": 40 10 | }, 11 | { 12 | "name": "noise", 13 | "color": "pink", 14 | "snr": 40 15 | }, 16 | { 17 | "name": "wow_flutter", 18 | "intensity": 1.3, 19 | "frequency": 0.55 20 | }, 21 | { 22 | "name": "normalize" 23 | } 24 | ] 25 | -------------------------------------------------------------------------------- /presets/smartphone_recording.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "impulse_response", 4 | "path": "./samples/IR_GoogleNexusOneFrontMic.wav" 5 | }, 6 | { 7 | "name": "dynamic_range_compression", 8 | "threshold": -35, 9 | "ratio": 2, 10 | "attack": 0.2, 11 | "release": 0.2 12 | }, 13 | { 14 | "name": "delay", 15 | "samples": 9600 16 | }, 17 | { 18 | "name": "clipping", 19 | "percent_samples": 0.3 20 | }, 21 | { 22 | "name": "noise", 23 | "color": "pink", 24 | "snr": 35 25 | }, 26 | { 27 | "name": "normalize" 28 | } 29 | ] 30 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/audio.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import array 3 | from pydub import AudioSegment 4 | from pydub.utils import get_array_type 5 | 6 | 7 | class Audio(object): 8 | def __init__( 9 | self, 10 | path=None, 11 | ext=None, 12 | samples=None, 13 | old_audio=None, 14 | sound=None, 15 | sample_rate=None, 16 | ): 17 | if ( 18 | (path and (samples is not None)) 19 | or (path and sound) 20 | or (sound and (samples is not None)) 21 | ): 22 | raise ValueError( 23 | "Only pass one of path[+ext] or samples[+old_audio] or sound[+old_audio]" 24 | ) 25 | 26 | if path: 27 | if not ext: 28 | ext = path.split(".")[-1] 29 | self.sound = AudioSegment.from_file(file=path, format=ext).set_channels(1) 30 | self.samples = self.sound.get_array_of_samples() 31 | self.sample_rate = self.sound.frame_rate 32 | self.format = ext 33 | if samples is not None: 34 | self.samples = samples 35 | if sample_rate: 36 | self.sample_rate = sample_rate 37 | else: 38 | self.sample_rate = old_audio.sample_rate 39 | self.sample_rate = int(self.sample_rate) 40 | self.sound = AudioSegment( 41 | data=self.samples, 42 | sample_width=old_audio.sound.sample_width, 43 | frame_rate=self.sample_rate, 44 | channels=1, 45 | ) 46 | self.format = old_audio.format 47 | if sound: 48 | self.sound = sound 49 | self.samples = self.sound.get_array_of_samples() 50 | self.sample_rate = sound.frame_rate 51 | self.format = old_audio.format 52 | 53 | def export(self, path): 54 | self.sound.export(out_f=path, format="wav") 55 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | 53 | # Translations 54 | *.mo 55 | *.pot 56 | 57 | # Django stuff: 58 | *.log 59 | local_settings.py 60 | db.sqlite3 61 | 62 | # Flask stuff: 63 | instance/ 64 | .webassets-cache 65 | 66 | # Scrapy stuff: 67 | .scrapy 68 | 69 | # Sphinx documentation 70 | docs/_build/ 71 | 72 | # PyBuilder 73 | target/ 74 | 75 | # Jupyter Notebook 76 | .ipynb_checkpoints 77 | 78 | # IPython 79 | profile_default/ 80 | ipython_config.py 81 | 82 | # pyenv 83 | .python-version 84 | 85 | # pipenv 86 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 87 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 88 | # having no cross-platform support, pipenv may install dependencies that don’t work, or not 89 | # install all needed dependencies. 90 | #Pipfile.lock 91 | 92 | # celery beat schedule file 93 | celerybeat-schedule 94 | 95 | # SageMath parsed files 96 | *.sage.py 97 | 98 | # Environments 99 | .env 100 | .venv 101 | env/ 102 | venv/ 103 | ENV/ 104 | env.bak/ 105 | venv.bak/ 106 | 107 | # Spyder project settings 108 | .spyderproject 109 | .spyproject 110 | 111 | # Rope project settings 112 | .ropeproject 113 | 114 | # mkdocs documentation 115 | /site 116 | 117 | # mypy 118 | .mypy_cache/ 119 | .dmypy.json 120 | dmypy.json 121 | 122 | # Pyre type checker 123 | .pyre/ 124 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/cli.py: -------------------------------------------------------------------------------- 1 | from .core import Degradation 2 | from .playback import playback_shim 3 | import argparse 4 | import json 5 | 6 | INTRO = """ 7 | Apply controlled degradations to an audio file, specified in a JSON file containing an array of degradations (executed in order). 8 | 9 | Paths are relative to the execution dir, and square brackets denote optional arguments along with their default values. 10 | 11 | { "name": "noise", ["snr": 20, "color": "pink"] } 12 | { "name": "mp3", ["bitrate": 320] } 13 | { "name": "gain", ["volume": 10.0] } 14 | { "name": "normalize" } 15 | { "name": "low_pass", ["cutoff": 1000.0] } 16 | { "name": "high_pass", ["cutoff": 1000.0] } 17 | { "name": "trim_millis", ["amount": 100, "offset": 0] } 18 | { "name": "mix", "path": STRING, ["snr": 20.0] } 19 | { "name": "speedup", "speed": FLOAT } 20 | { "name": "resample", "rate": INT } 21 | { "name": "pitch_shift", "octaves": FLOAT } 22 | { "name": "dynamic_range_compression", ["threshold": -20.0, "ratio": 4.0, "attack": 5.0, "release": 50.0] } 23 | { "name": "impulse_response", "path": STRING } 24 | { "name": "equalizer", "frequency": FLOAT, ["bandwidth": 1.0, "gain": -3.0] } 25 | { "name": "time_stretch", "factor": FLOAT } 26 | { "name": "delay", "samples": INT } 27 | { "name": "clipping", ["samples": 0, "percent_samples": 0.0] } 28 | { "name": "wow_flutter", ["intensity": 1.5, "frequency": 0.5, "upsampling_factor": 5.0 ] } 29 | { "name": "aliasing", ["dest_frequency": 8000.0] } 30 | { "name": "harmonic_distortion", ["num_passes": 3] } 31 | """ 32 | 33 | 34 | def main(): 35 | parser = argparse.ArgumentParser( 36 | prog="audio-degradation-toolbox", 37 | description=INTRO, 38 | formatter_class=argparse.RawDescriptionHelpFormatter, 39 | ) 40 | 41 | parser.add_argument( 42 | "-d", "--degradations-file", help="JSON file of degradations to apply" 43 | ) 44 | parser.add_argument( 45 | "-p", 46 | "--play", 47 | action="store_true", 48 | help="Play file audio at each degradation step", 49 | ) 50 | parser.add_argument( 51 | "-t", "--trim", action="store_true", help="Trim trailing and leading silences" 52 | ) 53 | parser.add_argument("input_path", help="Path to input file") 54 | parser.add_argument("output_path", help="Path to output WAV file") 55 | args = parser.parse_args() 56 | 57 | deg = Degradation(path=args.input_path, trim_on_load=args.trim) 58 | 59 | if args.degradations_file: 60 | with open(args.degradations_file) as f: 61 | degradations = json.load(f) 62 | 63 | if args.play: 64 | print("Playing audio before degradations") 65 | playback_shim(deg.file_audio) 66 | 67 | for degradation in degradations: 68 | deg.apply_degradation(degradation, play_=args.play) 69 | 70 | deg.file_audio.export(args.output_path) 71 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | import io 5 | import os 6 | import sys 7 | from shutil import rmtree 8 | 9 | from setuptools import find_packages, setup, Command 10 | 11 | # Package meta-data. 12 | NAME = 'audio-degradation-toolbox' 13 | DESCRIPTION = 'Controlled audio degradations to evaluate DSP algorithms' 14 | URL = 'https://github.com/sevagh/audio-degradation-toolbox' 15 | EMAIL = 'sevag.hanssian@gmail.com' 16 | AUTHOR = 'Sevag Hanssian' 17 | REQUIRES_PYTHON = '>=3.6.0' 18 | VERSION = None 19 | 20 | REQUIRED = [] 21 | with open("./requirements.txt") as f: 22 | for l in f: 23 | REQUIRED.append(l[:-1]) 24 | 25 | EXTRAS = [ 26 | #'python-mpv' 27 | ] 28 | 29 | here = os.path.abspath(os.path.dirname(__file__)) 30 | 31 | try: 32 | with io.open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 33 | long_description = '\n' + f.read() 34 | except FileNotFoundError: 35 | long_description = DESCRIPTION 36 | 37 | # Load the package's __version__.py module as a dictionary. 38 | about = {} 39 | if not VERSION: 40 | project_slug = NAME.lower().replace("-", "_").replace(" ", "_") 41 | with open(os.path.join(here, project_slug, '__version__.py')) as f: 42 | exec(f.read(), about) 43 | else: 44 | about['__version__'] = VERSION 45 | 46 | 47 | class UploadCommand(Command): 48 | """Support setup.py upload.""" 49 | 50 | description = 'Build and publish the package.' 51 | user_options = [] 52 | 53 | @staticmethod 54 | def status(s): 55 | """Prints things in bold.""" 56 | print('\033[1m{0}\033[0m'.format(s)) 57 | 58 | def initialize_options(self): 59 | pass 60 | 61 | def finalize_options(self): 62 | pass 63 | 64 | def run(self): 65 | try: 66 | self.status('Removing previous builds…') 67 | rmtree(os.path.join(here, 'dist')) 68 | except OSError: 69 | pass 70 | 71 | self.status('Building Source and Wheel (universal) distribution…') 72 | os.system('{0} setup.py sdist bdist_wheel --universal'.format(sys.executable)) 73 | 74 | self.status('Uploading the package to PyPI via Twine…') 75 | os.system('twine upload dist/*') 76 | 77 | self.status('Pushing git tags…') 78 | os.system('git tag v{0}'.format(about['__version__'])) 79 | os.system('git push --tags') 80 | 81 | sys.exit() 82 | 83 | 84 | # Where the magic happens: 85 | setup( 86 | name=NAME, 87 | version=about['__version__'], 88 | description=DESCRIPTION, 89 | long_description=long_description, 90 | long_description_content_type='text/markdown', 91 | author=AUTHOR, 92 | author_email=EMAIL, 93 | python_requires=REQUIRES_PYTHON, 94 | url=URL, 95 | packages=find_packages(exclude=('tests',)), 96 | py_modules=['audio_degradation_toolbox'], 97 | entry_points={ 98 | 'console_scripts': ['audio-degradation-toolbox=audio_degradation_toolbox.cli:main'], 99 | }, 100 | install_requires=REQUIRED, 101 | extra_requires=EXTRAS, 102 | include_package_data=True, 103 | license='MIT', 104 | classifiers=[ 105 | # Trove classifiers 106 | # Full list: https://pypi.python.org/pypi?%3Aaction=list_classifiers 107 | ], 108 | # $ setup.py publish support. 109 | cmdclass={ 110 | 'upload': UploadCommand, 111 | }, 112 | ) 113 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Python 3 implementation of the MATLAB [Audio Degradation Toolbox](https://code.soundsoftware.ac.uk/projects/audio-degradation-toolbox). The license is GPL due to the original code being GPL. The aim is full feature parity with: 2 | 3 | * Original MATLAB toolbox (with ISMIR2013 additions) 4 | * A similar tool, [audio_degrader](https://github.com/EliosMolina/audio_degrader) 5 | 6 | This tool can read non-WAV files as input, but only outputs single-channel WAV files - this is because I find that WAV is the most universal format with friendly-licensed libraries in any language. 7 | 8 | ### Available degradations 9 | 10 | ``` 11 | $ audio-degradation-toolbox -h 12 | usage: audio-degradation-toolbox [-h] [-d DEGRADATIONS_FILE] [-p] [-t] 13 | input_path output_path 14 | 15 | Apply controlled degradations to an audio file, specified in a JSON file containing an array of degradations (executed in order). 16 | 17 | Paths are relative to the execution dir, and square brackets denote optional arguments along with their default values. 18 | 19 | { "name": "noise", ["snr": 20, "color": "pink"] } 20 | { "name": "mp3", ["bitrate": 320] } 21 | { "name": "gain", ["volume": 10.0] } 22 | { "name": "normalize" } 23 | { "name": "low_pass", ["cutoff": 1000.0] } 24 | { "name": "high_pass", ["cutoff": 1000.0] } 25 | { "name": "trim_millis", ["amount": 100, "offset": 0] } 26 | { "name": "mix", "path": STRING, ["snr": 20.0] } 27 | { "name": "speedup", "speed": FLOAT } 28 | { "name": "resample", "rate": INT } 29 | { "name": "pitch_shift", "octaves": FLOAT } 30 | { "name": "dynamic_range_compression", ["threshold": -20.0, "ratio": 4.0, "attack": 5.0, "release": 50.0] } 31 | { "name": "impulse_response", "path": STRING } 32 | { "name": "equalizer", "frequency": FLOAT, ["bandwidth": 1.0, "gain": -3.0] } 33 | { "name": "time_stretch", "factor": FLOAT } 34 | { "name": "delay", "n_samples": INT } 35 | { "name": "clipping", ["n_samples": 0, "percent_samples": 0.0] } 36 | { "name": "wow_flutter", ["intensity": 1.5, "frequency": 0.5, "upsampling_factor": 5.0 ] } 37 | { "name": "aliasing", ["dest_frequency": 8000.0] } 38 | { "name": "harmonic_distortion", ["num_passes": 3] } 39 | 40 | positional arguments: 41 | input_path Path to input file 42 | output_path Path to output WAV file 43 | 44 | optional arguments: 45 | -h, --help show this help message and exit 46 | -d DEGRADATIONS_FILE, --degradations-file DEGRADATIONS_FILE 47 | JSON file of degradations to apply 48 | -p, --play Play file audio at each degradation step 49 | -t, --trim Trim trailing and leading silences 50 | ``` 51 | 52 | ### Presets and samples 53 | 54 | Some of the ISMIR2013 degradations are chains of basic degradations. Given the JSON format that my tool accepts, these are most easily represented as JSON files in the [presets](./presets) dir. 55 | 56 | [Samples](./samples), mostly IR wav files, come from the original MATLAB repository. I've resampled them from 96000 to 48000 with ffmpeg, since pydub has questionable support for 96000. 57 | 58 | ### Install, develop, contribute 59 | 60 | It should be as easy as `pip3 install .` after cloning this repository. Afterwards, run `audio-degradation-toolbox`. You may need to install `sox` from your OS package manager for some effects. 61 | 62 | To develop, `pip3 install -e .`. The code is formatted with [black](https://github.com/ambv/black), so run that before contributing anything. To run tests, run `python3 -m unittest discover`. 63 | 64 | To use the `--play` flag (i.e. play the audio clip between each degradation), you must have `mpv` installed and in `$PATH`: 65 | 66 | ``` 67 | sevagh:audio-degradation-toolbox $ audio-degradation-toolbox \ 68 | Viola.arco.ff.sulC.E3.stereo.aiff \ 69 | Viola-E3-degraded.wav \ 70 | --degradations-file ./degradations.json \ 71 | --play 72 | Playing audio before degradations 73 | A: 00:00:03 / 00:00:03 (93%) 74 | Applied degradation noise with params color: white, snr: 20 75 | Playing audio after degradation 76 | A: 00:00:03 / 00:00:03 (93%) 77 | ``` 78 | 79 | ### Usage 80 | 81 | Write the desired degradations in a JSON file, e.g.: 82 | 83 | ``` 84 | $ cat degradations.json 85 | [ 86 | { 87 | "name": "trim_millis", 88 | "amount": 500 89 | }, 90 | { 91 | "name": "noise", 92 | "color": "violet", 93 | "snr": 10 94 | }, 95 | { 96 | "name": "mix", 97 | "path": "./restaurant08.wav", 98 | "snr": 15 99 | } 100 | ] 101 | ``` 102 | 103 | Afterwards, apply the degradations with: 104 | 105 | ``` 106 | $ audio-degradation-toolbox -d degradations.json in.wav out_degraded.wav 107 | ``` 108 | 109 | ### Unimplemented 110 | 111 | MfccMeanAdaption and AdaptiveEqualizer (both from the MATLAB original). 112 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/core.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | from pydub import AudioSegment 3 | from pydub.utils import get_array_type 4 | from .playback import playback_shim 5 | from acoustics import Signal 6 | from acoustics.generator import noise 7 | import math 8 | from tempfile import NamedTemporaryFile 9 | from .degradations import ( 10 | trim, 11 | apply_noise, 12 | apply_mix, 13 | mp3_transcode, 14 | apply_gain, 15 | apply_normalization, 16 | apply_high_pass, 17 | apply_low_pass, 18 | trim_millis, 19 | apply_speedup, 20 | apply_resample, 21 | apply_pitch_shift, 22 | apply_dynamic_range_compression, 23 | apply_impulse_response, 24 | apply_time_stretch, 25 | apply_eq, 26 | apply_delay, 27 | apply_clipping, 28 | apply_wow_flutter, 29 | apply_aliasing, 30 | apply_harmonic_distortion, 31 | ) 32 | from .audio import Audio 33 | 34 | 35 | class Degradation(object): 36 | def __init__(self, path, ext=None, trim_on_load=False): 37 | self.file_audio = Audio(path, ext=ext) 38 | if trim_on_load: 39 | self.file_audio = trim(self.file_audio) 40 | 41 | def apply_degradation(self, d, play_=False): 42 | name = d["name"] 43 | params = "" 44 | 45 | if name == "noise": 46 | color = d.get("color", "pink") 47 | snr = d.get("snr", 20) 48 | params = "color: {0}, snr: {1}".format(color, snr) 49 | self.file_audio = apply_noise(self.file_audio, color, snr) 50 | elif name == "mp3": 51 | bitrate = d.get("bitrate", 320) 52 | params = "bitrate: {0}".format(bitrate) 53 | self.file_audio = mp3_transcode(self.file_audio, bitrate) 54 | elif name == "gain": 55 | volume = float(d.get("volume", 10.0)) 56 | self.file_audio = apply_gain(self.file_audio, volume) 57 | params = "volume: {0}".format(volume) 58 | elif name == "normalize": 59 | self.file_audio = apply_normalization(self.file_audio) 60 | elif name == "low_pass": 61 | cutoff = float(d.get("cutoff", 1000.0)) 62 | self.file_audio = apply_low_pass(self.file_audio, cutoff) 63 | params = "cutoff: {0}".format(cutoff) 64 | elif name == "high_pass": 65 | cutoff = float(d.get("cutoff", 1000.0)) 66 | self.file_audio = apply_high_pass(self.file_audio, cutoff) 67 | params = "cutoff: {0}".format(cutoff) 68 | elif name == "trim_millis": 69 | amount = int(d.get("amount", 100)) 70 | offset = int(d.get("offset", 0)) 71 | self.file_audio = trim_millis(self.file_audio, amount, offset) 72 | params = "amount: {0}, offset: {1}".format(amount, offset) 73 | elif name == "mix": 74 | mix_path = d["path"] 75 | snr = float(d.get("snr", 20.0)) 76 | self.file_audio = apply_mix(self.file_audio, mix_path, snr) 77 | params = "mix_path: {0}, snr: {1}".format(mix_path, snr) 78 | elif name == "speedup": 79 | speed = float(d["speed"]) 80 | self.file_audio = apply_speedup(self.file_audio, speed) 81 | params = "speed: {0}".format(speed) 82 | elif name == "resample": 83 | rate = int(d["rate"]) 84 | self.file_audio = apply_resample(self.file_audio, rate) 85 | params = "rate: {0}".format(rate) 86 | elif name == "pitch_shift": 87 | octaves = float(d["octaves"]) 88 | self.file_audio = apply_pitch_shift(self.file_audio, octaves) 89 | params = "octaves: {0}".format(octaves) 90 | elif name == "dynamic_range_compression": 91 | threshold = float(d.get("threshold", -20.0)) 92 | ratio = float(d.get("ratio", 4.0)) 93 | attack = float(d.get("attack", 5.0)) 94 | release = float(d.get("release", 50.0)) 95 | self.file_audio = apply_dynamic_range_compression( 96 | self.file_audio, threshold, ratio, attack, release 97 | ) 98 | params = "threshold: {0}, ratio: {1}, attack: {2}, release: {3}".format( 99 | threshold, ratio, attack, release 100 | ) 101 | elif name == "impulse_response": 102 | path = d["path"] 103 | self.file_audio = apply_impulse_response(self.file_audio, path) 104 | params = "path: {0}".format(path) 105 | elif name == "equalizer": 106 | frequency = float(d["frequency"]) 107 | bandwidth = float(d.get("bandwidth", 1.0)) 108 | gain = float(d.get("gain", -3.0)) 109 | self.file_audio = apply_eq(self.file_audio, frequency, bandwidth, gain) 110 | params = "frequency: {0}, bandwidth: {1}, gain: {2}".format( 111 | frequency, bandwidth, gain 112 | ) 113 | elif name == "time_stretch": 114 | factor = float(d["factor"]) 115 | self.file_audio = apply_time_stretch(self.file_audio, factor) 116 | params = "factor: {0}".format(factor) 117 | elif name == "delay": 118 | n_samples = int(d["samples"]) 119 | self.file_audio = apply_delay(self.file_audio, n_samples) 120 | params = "samples: {0}".format(n_samples) 121 | elif name == "clipping": 122 | n_samples = int(d.get("samples", 0)) 123 | percent_samples = float(d.get("percent_samples", 0.0)) / 100.0 124 | self.file_audio = apply_clipping( 125 | self.file_audio, n_samples, percent_samples 126 | ) 127 | params = "samples: {0}, percent_samples: {1}".format( 128 | n_samples, percent_samples 129 | ) 130 | elif name == "wow_flutter": 131 | intensity = float(d.get("intensity", 1.5)) 132 | frequency = float(d.get("frequency", 0.5)) 133 | upsampling_factor = float(d.get("upsampling_factor", 5.0)) 134 | self.file_audio = apply_wow_flutter( 135 | self.file_audio, intensity, frequency, upsampling_factor 136 | ) 137 | params = "intensity: {0}, frequency: {1}, upsampling_factor: {2}".format( 138 | intensity, frequency, upsampling_factor 139 | ) 140 | elif name == "aliasing": 141 | dest_frequency = float(d.get("dest_frequency", 8000.0)) 142 | self.file_audio = apply_aliasing(self.file_audio, dest_frequency) 143 | params = "dest_frequency: {0}".format(dest_frequency) 144 | elif name == "harmonic_distortion": 145 | num_passes = int(d.get("num_passes", 3)) 146 | self.file_audio = apply_harmonic_distortion(self.file_audio, num_passes) 147 | params = "num_passes: {0}".format(num_passes) 148 | else: 149 | raise ValueError("Invalid degradation {0}".format(name)) 150 | 151 | print( 152 | "Applied degradation {0}{1}".format( 153 | name, " with params {0}".format(params) if params else "" 154 | ) 155 | ) 156 | if play_: 157 | print("Playing audio after degradation") 158 | playback_shim(self.file_audio) 159 | -------------------------------------------------------------------------------- /tests/test_audio_degradation_toolbox.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from audio_degradation_toolbox.core import Degradation 3 | import numpy 4 | import scipy.signal as scipy_signal 5 | import math 6 | import copy 7 | import numba 8 | 9 | 10 | # https://gist.github.com/sebpiq/4128537 11 | def goertzel(samples, sample_rate, *freqs): 12 | window_size = len(samples) 13 | f_step = sample_rate / float(window_size) 14 | f_step_normalized = 1.0 / window_size 15 | 16 | bins = set() 17 | for f_range in freqs: 18 | f_start, f_end = f_range 19 | k_start = int(math.floor(f_start / f_step)) 20 | k_end = int(math.ceil(f_end / f_step)) 21 | 22 | if k_end > window_size - 1: 23 | raise ValueError("frequency out of range %s" % k_end) 24 | bins = bins.union(range(k_start, k_end)) 25 | 26 | n_range = range(0, window_size) 27 | freqs = [] 28 | results = [] 29 | for k in bins: 30 | 31 | f = k * f_step_normalized 32 | w_real = 2.0 * math.cos(2.0 * math.pi * f) 33 | w_imag = math.sin(2.0 * math.pi * f) 34 | 35 | d1, d2 = 0.0, 0.0 36 | for n in n_range: 37 | y = samples[n] + w_real * d1 - d2 38 | d2, d1 = d1, y 39 | 40 | results.append( 41 | (0.5 * w_real * d1 - d2, w_imag * d1, d2 ** 2 + d1 ** 2 - w_real * d1 * d2) 42 | ) 43 | freqs.append(f * sample_rate) 44 | 45 | power = 0 46 | for r in results: 47 | power += r[2] 48 | return power 49 | 50 | 51 | class TestAllDegradations(unittest.TestCase): 52 | @classmethod 53 | def setUpClass(cls): 54 | # don't reload the file so many times 55 | cls.orig_d = Degradation("./samples/Viola.arco.ff.sulC.E3.stereo.aiff") 56 | 57 | def setUp(self): 58 | self.d = copy.deepcopy(self.orig_d) 59 | 60 | def test_basic(self): 61 | self.assertEqual(self.d.file_audio.sample_rate, 44100) 62 | self.assertEqual(len(self.d.file_audio.sound), 3664) 63 | 64 | def test_noise(self): 65 | prev_mean = numpy.mean( 66 | numpy.frombuffer( 67 | self.d.file_audio.samples, dtype=self.d.file_audio.sound.array_type 68 | ) 69 | ) 70 | 71 | noises = [ 72 | {"name": "noise", "color": "pink"}, 73 | {"name": "noise", "color": "white", "snr": 30}, 74 | {"name": "noise", "color": "brown", "snr": 10}, 75 | {"name": "noise", "color": "blue", "snr": 20}, 76 | {"name": "noise", "color": "violet", "snr": 15}, 77 | ] 78 | 79 | for noise in noises: 80 | self.d.apply_degradation(noise) 81 | new_mean = numpy.mean( 82 | numpy.frombuffer( 83 | self.d.file_audio.samples, dtype=self.d.file_audio.sound.array_type 84 | ) 85 | ) 86 | # ensure the signal has a different mean after noise 87 | self.assertNotEqual(new_mean, prev_mean) 88 | prev_mean = new_mean 89 | 90 | # noise won't affect the length 91 | self.assertEqual(len(self.d.file_audio.sound), 3664) 92 | 93 | def test_mp3(self): 94 | mp3s = [ 95 | {"name": "mp3"}, 96 | {"name": "mp3", "bitrate": 128}, 97 | {"name": "mp3", "bitrate": 64}, 98 | ] 99 | 100 | for mp3 in mp3s: 101 | self.d.apply_degradation(mp3) 102 | 103 | self.assertTrue(len(self.d.file_audio.sound) > 3664) 104 | 105 | def test_gain(self): 106 | prev_max = numpy.max( 107 | numpy.frombuffer( 108 | self.d.file_audio.samples, dtype=self.d.file_audio.sound.array_type 109 | ) 110 | ) 111 | 112 | gains = [ 113 | {"name": "gain"}, 114 | {"name": "gain", "volume": -10}, 115 | {"name": "gain", "volume": 10}, 116 | ] 117 | 118 | for gain in gains: 119 | self.d.apply_degradation(gain) 120 | new_max = numpy.max( 121 | numpy.frombuffer( 122 | self.d.file_audio.samples, dtype=self.d.file_audio.sound.array_type 123 | ) 124 | ) 125 | if gain.get("volume", 10) < 0: 126 | self.assertTrue(new_max < prev_max) 127 | else: 128 | self.assertTrue(new_max >= prev_max) 129 | prev_max = new_max 130 | 131 | def test_normalize(self): 132 | normalize = {"name": "normalize"} 133 | self.d.apply_degradation(normalize) 134 | 135 | def test_low_pass(self): 136 | # our input is E3 aka 160ish hz 137 | old_pwr = goertzel( 138 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 139 | ) 140 | 141 | low_pass = {"name": "low_pass", "cutoff": 100} 142 | self.d.apply_degradation(low_pass) 143 | new_pwr = goertzel( 144 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 145 | ) 146 | 147 | self.assertTrue(new_pwr < old_pwr) 148 | 149 | def test_high_pass(self): 150 | # our input is E3 aka 160ish hz 151 | old_pwr = goertzel( 152 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 153 | ) 154 | 155 | high_pass = {"name": "high_pass", "cutoff": 200} 156 | self.d.apply_degradation(high_pass) 157 | new_pwr = goertzel( 158 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 159 | ) 160 | 161 | self.assertTrue(new_pwr < old_pwr) 162 | 163 | def test_trim_millis(self): 164 | trim_left = {"name": "trim_millis"} 165 | trim_right = {"name": "trim_millis", "offset": -1, "amount": 500} 166 | self.d.apply_degradation(trim_left) 167 | self.d.apply_degradation(trim_right) 168 | 169 | self.assertEqual(len(self.d.file_audio.sound), 3664 - 100 - 500) 170 | 171 | def test_mix(self): 172 | # our input is E3 aka 160ish hz 173 | old_pwr = goertzel( 174 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 175 | ) 176 | 177 | mix = {"name": "mix", "path": "./samples/Viola.arco.ff.sulC.E3.stereo.aiff"} 178 | self.d.apply_degradation(mix) 179 | new_pwr = goertzel( 180 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 181 | ) 182 | 183 | self.assertTrue(new_pwr > old_pwr) 184 | 185 | def test_speedup(self): 186 | speedup = {"name": "speedup", "speed": 1.05} 187 | old_fs = self.d.file_audio.sample_rate 188 | self.d.apply_degradation(speedup) 189 | 190 | self.assertEqual(old_fs / 1.05, self.d.file_audio.sample_rate) 191 | old_fs = self.d.file_audio.sample_rate 192 | 193 | speedup = {"name": "speedup", "speed": 0.95} 194 | self.d.apply_degradation(speedup) 195 | 196 | self.assertEqual(math.floor(old_fs / 0.95), self.d.file_audio.sample_rate) 197 | 198 | def test_resample(self): 199 | resample = {"name": "resample", "rate": 96000} 200 | self.assertNotEqual(self.d.file_audio.sample_rate, 96000) 201 | self.d.apply_degradation(resample) 202 | self.assertEqual(self.d.file_audio.sample_rate, 96000) 203 | 204 | def test_pitch_shift(self): 205 | # our input is E3 aka 160ish hz 206 | old_pwr = goertzel( 207 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 208 | ) 209 | 210 | pitch_shift = {"name": "pitch_shift", "octaves": -1.0} 211 | 212 | self.d.apply_degradation(pitch_shift) 213 | new_pwr = goertzel( 214 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 215 | ) 216 | 217 | self.assertTrue(new_pwr < old_pwr) 218 | 219 | def test_dynamic_range_compression(self): 220 | old_pwr = goertzel( 221 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 222 | ) 223 | 224 | drcs = [ 225 | {"name": "dynamic_range_compression"}, 226 | {"name": "dynamic_range_compression", "threshold": -15.0, "ratio": 3.0}, 227 | {"name": "dynamic_range_compression", "threshold": -15.0, "attack": 4.0}, 228 | {"name": "dynamic_range_compression", "release": 42.0}, 229 | ] 230 | 231 | for drc in drcs: 232 | self.d.apply_degradation(drc) 233 | new_pwr = goertzel( 234 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 235 | ) 236 | 237 | self.assertTrue(new_pwr < old_pwr) 238 | 239 | def test_ir(self): 240 | old_pwr = goertzel( 241 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 242 | ) 243 | 244 | ir = {"name": "impulse_response", "path": "./samples/IR_GreatHall.wav"} 245 | self.d.apply_degradation(ir) 246 | new_pwr = goertzel( 247 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 248 | ) 249 | 250 | self.assertTrue(new_pwr > old_pwr) 251 | 252 | def test_eq(self): 253 | old_pwr = goertzel( 254 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 255 | ) 256 | 257 | eq = {"name": "equalizer", "frequency": 163} 258 | self.d.apply_degradation(eq) 259 | new_pwr = goertzel( 260 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 261 | ) 262 | 263 | self.assertTrue(new_pwr > old_pwr) 264 | 265 | def test_time_stretch(self): 266 | ts = {"name": "time_stretch", "factor": 2.0} 267 | self.d.apply_degradation(ts) 268 | self.assertTrue(3664 / 2.1 <= len(self.d.file_audio.sound) <= 3664 / 2.0) 269 | 270 | def test_delay(self): 271 | delay = {"name": "delay", "samples": 44100} 272 | self.d.apply_degradation(delay) 273 | self.assertEqual(len(self.d.file_audio.sound), 3664 + 1000) 274 | 275 | def test_clipping(self): 276 | _, old_pwr = scipy_signal.welch( 277 | self.d.file_audio.samples, self.d.file_audio.sample_rate 278 | ) 279 | old_pwr = numpy.sum(old_pwr) 280 | 281 | clip = {"name": "clipping", "percent_samples": 50} 282 | self.d.apply_degradation(clip) 283 | 284 | _, new_pwr = scipy_signal.welch( 285 | self.d.file_audio.samples, self.d.file_audio.sample_rate 286 | ) 287 | new_pwr = numpy.sum(new_pwr) 288 | 289 | self.assertTrue(new_pwr > old_pwr) 290 | 291 | def test_wow_flutter(self): 292 | old_pwr = goertzel( 293 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 294 | ) 295 | 296 | wfs = [ 297 | {"name": "wow_flutter"}, 298 | { 299 | "name": "wow_flutter", 300 | "intensity": 3.0, 301 | "frequency": 0.5, 302 | "upsampling_factor": 1.0, 303 | }, 304 | ] 305 | 306 | for wf in wfs: 307 | self.d.apply_degradation(wf) 308 | new_pwr = goertzel( 309 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 310 | ) 311 | self.assertTrue(new_pwr < old_pwr) 312 | 313 | def test_aliasing(self): 314 | old_pwr = goertzel( 315 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 316 | ) 317 | 318 | aliasing = {"name": "aliasing", "dest_frequency": 82.4} 319 | self.d.apply_degradation(aliasing) 320 | 321 | new_pwr = goertzel( 322 | self.d.file_audio.samples, self.d.file_audio.sample_rate, (162, 164) 323 | ) 324 | self.assertTrue(new_pwr < old_pwr) 325 | 326 | def test_harmonic_distortion(self): 327 | _, old_pwr = scipy_signal.welch( 328 | self.d.file_audio.samples, self.d.file_audio.sample_rate 329 | ) 330 | old_pwr = numpy.sum(old_pwr) 331 | 332 | hd = {"name": "harmonic_distortion", "num_passes": 5} 333 | self.d.apply_degradation(hd) 334 | 335 | _, new_pwr = scipy_signal.welch( 336 | self.d.file_audio.samples, self.d.file_audio.sample_rate 337 | ) 338 | new_pwr = numpy.sum(new_pwr) 339 | 340 | self.assertTrue(new_pwr > old_pwr) 341 | 342 | 343 | if __name__ == "__main__": 344 | unittest.main() 345 | -------------------------------------------------------------------------------- /audio_degradation_toolbox/degradations.py: -------------------------------------------------------------------------------- 1 | import numpy 2 | import pydub.effects as pydub_effects 3 | import pydub.scipy_effects 4 | from acoustics.generator import noise 5 | import math 6 | from tempfile import NamedTemporaryFile 7 | from .audio import Audio 8 | import array 9 | import sys 10 | import scipy.signal as scipy_signal 11 | import scipy.interpolate as scipy_interpolate 12 | import librosa 13 | import numba 14 | from pysndfx import AudioEffectsChain 15 | 16 | 17 | def mp3_transcode(audio, bitrate): 18 | # do a pydub round trip through an mp3 file 19 | ret = None 20 | with NamedTemporaryFile() as tmp_mp3_f: 21 | audio.sound.export( 22 | out_f=tmp_mp3_f.name, format="mp3", bitrate="{0}k".format(bitrate) 23 | ) 24 | ret = Audio(path=tmp_mp3_f, ext="mp3") 25 | return ret 26 | 27 | 28 | def apply_gain(audio, gain_dbs): 29 | return Audio(sound=audio.sound.apply_gain(gain_dbs), old_audio=audio) 30 | 31 | 32 | def apply_normalization(audio): 33 | return Audio(sound=pydub_effects.normalize(audio.sound), old_audio=audio) 34 | 35 | 36 | def apply_low_pass(audio, cutoff): 37 | return Audio( 38 | sound=pydub_effects.low_pass_filter(audio.sound, cutoff), old_audio=audio 39 | ) 40 | 41 | 42 | def apply_high_pass(audio, cutoff): 43 | return Audio( 44 | sound=pydub_effects.high_pass_filter(audio.sound, cutoff), old_audio=audio 45 | ) 46 | 47 | 48 | def trim_millis(audio, amount, offset): 49 | if amount >= len(audio.sound): 50 | print( 51 | "Not trimming amount {0} longer than file {1}".format( 52 | amount, len(audio.sound) 53 | ), 54 | file=sys.stderr, 55 | ) 56 | return audio 57 | 58 | ret = None 59 | if offset == -1: 60 | ret = Audio(sound=audio.sound[: len(audio.sound) - amount], old_audio=audio) 61 | else: 62 | ret = Audio( 63 | sound=(audio.sound[: offset + 1] + audio.sound[offset + amount + 1 :]), 64 | old_audio=audio, 65 | ) 66 | 67 | print("New length: {0}".format(len(ret.sound))) 68 | return ret 69 | 70 | 71 | def apply_mix(audio, mix, snr): 72 | mix_audio = Audio(path=mix) 73 | mix_audio = _stretch_mix(audio, mix_audio) 74 | 75 | mix_data = numpy.frombuffer( 76 | mix_audio.samples, dtype=mix_audio.sound.array_type 77 | ).astype(numpy.float64) 78 | return _mix(audio, mix_data, snr) 79 | 80 | 81 | def apply_noise(audio, color, snr): 82 | noise_data = noise(len(audio.samples), color=color) 83 | return _mix(audio, noise_data, snr) 84 | 85 | 86 | def apply_speedup(audio, speed): 87 | return apply_resample(audio, audio.sample_rate / speed) 88 | 89 | 90 | def apply_resample(audio, new_sample_rate): 91 | int_sample_rate = int(new_sample_rate) 92 | return Audio(sound=audio.sound.set_frame_rate(int_sample_rate), old_audio=audio) 93 | 94 | 95 | def apply_pitch_shift(audio, octaves): 96 | new_sample_rate = int(audio.sample_rate * (2.0 ** octaves)) 97 | return apply_resample(audio, new_sample_rate) 98 | 99 | 100 | def apply_dynamic_range_compression(audio, threshold, ratio, attack, release): 101 | return Audio( 102 | sound=pydub_effects.compress_dynamic_range( 103 | audio.sound, threshold, ratio, attack, release 104 | ), 105 | old_audio=audio, 106 | ) 107 | 108 | 109 | def apply_impulse_response(audio, ir_path): 110 | ir = Audio(path=ir_path) 111 | 112 | if ir.sample_rate != audio.sample_rate: 113 | ir = apply_resample(ir, audio.sample_rate) 114 | 115 | conv_s = scipy_signal.fftconvolve(audio.samples, ir.samples) 116 | conv_s = _normalize(conv_s, audio.sound.sample_width * 8) 117 | 118 | conv_s = array.array(audio.sound.array_type, conv_s.astype(audio.sound.array_type)) 119 | 120 | conv = Audio(samples=conv_s, old_audio=audio) 121 | return conv 122 | 123 | 124 | def apply_time_stretch(audio, factor): 125 | samples = numpy.frombuffer(audio.samples, dtype=audio.sound.array_type).astype( 126 | numpy.float64 127 | ) 128 | stretched = librosa.effects.time_stretch(samples, factor) 129 | stretched = _normalize(stretched, audio.sound.sample_width * 8) 130 | 131 | return Audio( 132 | samples=array.array( 133 | audio.sound.array_type, stretched.astype(audio.sound.array_type) 134 | ), 135 | old_audio=audio, 136 | ) 137 | 138 | 139 | def trim(audio): 140 | samples = numpy.frombuffer(audio.samples, dtype=audio.sound.array_type).astype( 141 | numpy.float64 142 | ) 143 | trimmed, _ = librosa.effects.trim(samples) 144 | trimmed = _normalize(trimmed, audio.sound.sample_width * 8) 145 | 146 | return Audio( 147 | samples=array.array( 148 | audio.sound.array_type, trimmed.astype(audio.sound.array_type) 149 | ), 150 | old_audio=audio, 151 | ) 152 | 153 | 154 | def apply_eq(audio, frequency, q, db): 155 | fx = AudioEffectsChain().equalizer(frequency, q, db) 156 | 157 | samples = numpy.frombuffer(audio.samples, dtype=audio.sound.array_type).astype( 158 | numpy.float64 159 | ) 160 | 161 | samples = fx(samples) 162 | samples = _normalize(samples, audio.sound.sample_width * 8) 163 | 164 | return Audio( 165 | samples=array.array( 166 | audio.sound.array_type, samples.astype(audio.sound.array_type) 167 | ), 168 | old_audio=audio, 169 | ) 170 | 171 | 172 | def apply_delay(audio, n_samples): 173 | samples = ( 174 | array.array(audio.sound.array_type, [0 for _ in range(n_samples)]) 175 | + audio.samples 176 | ) 177 | return Audio(samples=samples, old_audio=audio) 178 | 179 | 180 | def apply_clipping(audio, n_samples, percent_samples): 181 | if n_samples != 0 and percent_samples != 0.0: 182 | raise ValueError("only specify one of samples or percent_samples") 183 | 184 | def db2mag(ydb): 185 | y = math.pow(10, ydb / 20) 186 | return y 187 | 188 | eps = numpy.spacing(1) 189 | 190 | samples = numpy.frombuffer(audio.samples, dtype=audio.sound.array_type).astype( 191 | numpy.complex 192 | ) 193 | 194 | if n_samples == 0 and percent_samples == 0.0: 195 | quant_measured = max( 196 | numpy.quantile(numpy.mean(numpy.power(samples, 2.2)), 0.95), eps 197 | ) 198 | quant_wanted = db2mag(-5) 199 | samples_out = samples * (quant_wanted / quant_measured) 200 | else: 201 | sorted_samples = numpy.abs(samples) 202 | sorted_samples.sort() 203 | num_samples = len(sorted_samples) 204 | if n_samples == 0: 205 | n_samples = int(percent_samples * num_samples) 206 | divisor = numpy.min(sorted_samples[num_samples - n_samples + 1 : num_samples]) 207 | divisor = max(divisor, eps) 208 | samples_out = samples / divisor 209 | 210 | samples_out = numpy.clip(samples_out, -1, 1) 211 | samples_out *= 0.99 212 | 213 | samples_out = _normalize(samples_out, audio.sound.sample_width * 8) 214 | 215 | return Audio( 216 | samples=array.array( 217 | audio.sound.array_type, samples_out.astype(audio.sound.array_type) 218 | ), 219 | old_audio=audio, 220 | ) 221 | 222 | 223 | # straight from matlab 224 | def apply_wow_flutter(audio, intensity, frequency, upsampling_factor): 225 | audio_out = audio.samples 226 | 227 | fs_oversampled = audio.sample_rate * upsampling_factor 228 | a_m = intensity / 100.0 229 | f_m = frequency 230 | 231 | num_samples = len(audio.samples) 232 | len_secs = len(audio.sound) / 1000.0 233 | num_full_periods = math.floor(len_secs * f_m) 234 | num_samples_to_warp = numpy.round(num_full_periods * audio.sample_rate / f_m) 235 | 236 | old_sample_positions_to_new_oversampled_positions = numpy.round( 237 | _time_assignment_new_to_old( 238 | numpy.arange(1, num_samples_to_warp) / audio.sample_rate, a_m, f_m 239 | ) 240 | * fs_oversampled 241 | ) 242 | 243 | audio_upsampled = apply_resample(audio, fs_oversampled).samples 244 | 245 | for i, pos in enumerate(old_sample_positions_to_new_oversampled_positions): 246 | audio_out[1 + i] = audio_upsampled[int(numpy.round(pos))] 247 | 248 | return Audio(samples=audio_out, sample_rate=fs_oversampled, old_audio=audio) 249 | 250 | 251 | # from matlab 252 | def apply_aliasing(audio, dest_frequency): 253 | n_samples = len(audio.samples) 254 | n_samples_new = int(numpy.round(n_samples / audio.sample_rate * dest_frequency)) 255 | t_old = numpy.arange(0.0, n_samples) / audio.sample_rate 256 | t_new = numpy.arange(0.0, n_samples_new) / dest_frequency 257 | 258 | audio_samples = numpy.frombuffer( 259 | audio.samples, dtype=audio.sound.array_type 260 | ).astype(numpy.float64) 261 | 262 | interp = scipy_interpolate.interp1d(t_old, audio_samples, kind="nearest") 263 | tmp = numpy.asarray([interp(t_new[x]) for x in range(len(t_new))], dtype=numpy.int) 264 | 265 | tmp_audio = Audio( 266 | samples=array.array(audio.sound.array_type, tmp), 267 | old_audio=audio, 268 | sample_rate=dest_frequency, 269 | ) 270 | return apply_resample(tmp_audio, audio.sample_rate) 271 | 272 | 273 | # quadratic distortion, approximated with sine (chebyshev polynomials?) 274 | def apply_harmonic_distortion(audio, num_passes): 275 | audio_samples = numpy.frombuffer( 276 | audio.samples, dtype=audio.sound.array_type 277 | ).astype(numpy.float64) 278 | 279 | # normalize to between -1 and 1 280 | a_min = audio_samples.min() 281 | a_max = audio_samples.max() 282 | 283 | audio_samples = numpy.interp(audio_samples, (a_min, a_max), (-1.0, +1.0)) 284 | 285 | for _ in range(num_passes): 286 | audio_samples = numpy.sin(audio_samples * (math.pi / 2.0)) 287 | 288 | # scale it back up? 289 | audio_samples = numpy.interp(audio_samples, (-1.0, +1.0), (a_min, a_max)) 290 | 291 | return Audio( 292 | samples=array.array(audio.sound.array_type, audio_samples.astype(numpy.int)), 293 | old_audio=audio, 294 | ) 295 | 296 | 297 | def trim(audio): 298 | samples = numpy.frombuffer(audio.samples, dtype=audio.sound.array_type).astype( 299 | numpy.float64 300 | ) 301 | trimmed, _ = librosa.effects.trim(samples) 302 | trimmed = _normalize(trimmed, audio.sound.sample_width * 8) 303 | 304 | return Audio( 305 | samples=array.array( 306 | audio.sound.array_type, trimmed.astype(audio.sound.array_type) 307 | ), 308 | old_audio=audio, 309 | ) 310 | 311 | 312 | def _mix(audio, mix_data, snr): 313 | Ps = 0 314 | Pn = 0 315 | 316 | for i in range(len(audio.samples)): 317 | Ps += abs(audio.samples[i]) * abs(audio.samples[i]) 318 | Pn += abs(mix_data[i]) * abs(mix_data[i]) 319 | Ps /= len(audio.samples) 320 | Pn /= len(audio.samples) 321 | 322 | k_factor = math.sqrt((Ps / Pn) * (10 ** (-snr / 10))) 323 | mix_data *= k_factor 324 | 325 | # some necessary casting to avoid fucking with the length of the audio file 326 | mix_data = array.array( 327 | audio.sound.array_type, mix_data.astype(audio.sound.array_type) 328 | ) 329 | 330 | for i in range(len(mix_data)): 331 | try: 332 | mix_data[i] += audio.samples[i] 333 | except OverflowError: 334 | try: 335 | mix_data[i] = numpy.finfo(mix_data.typecode).max 336 | except ValueError: 337 | mix_data[i] = numpy.iinfo(mix_data.typecode).max 338 | a = Audio(samples=mix_data, old_audio=audio) 339 | return a 340 | 341 | 342 | def _stretch_mix(audio, mix_audio): 343 | if len(mix_audio.samples) > len(audio.samples): 344 | mix_audio = Audio( 345 | samples=mix_audio.samples[: len(audio.samples)], old_audio=mix_audio 346 | ) 347 | elif len(mix_audio.samples) < len(audio.samples): 348 | m_s = mix_audio.samples 349 | while len(m_s) < len(audio.samples): 350 | m_s += m_s[ 351 | : min( 352 | len(audio.samples) - len(mix_audio.samples), len(mix_audio.samples) 353 | ) 354 | ] 355 | mix_audio = Audio(samples=m_s, old_audio=mix_audio) 356 | 357 | return mix_audio 358 | 359 | 360 | # thanks https://github.com/limmor1/Convolve 361 | def _normalize(y, bitwidth): 362 | if abs(numpy.amax(y)) > abs(numpy.amin(y)): 363 | larger = numpy.amax(y) 364 | else: 365 | larger = abs(numpy.amin(y)) 366 | y = y / larger * ((2 ** bitwidth / 2) - 1) 367 | return y 368 | 369 | 370 | # copied straight from matlab 371 | @numba.jit 372 | def _times_assignment_old_to_new(x, a_m, f_m): 373 | time_assigned = [0.0 for _ in len(x)] 374 | 375 | for i, elem in enumerate(x): 376 | time_assigned[i] = ( 377 | x[i] + a_m + math.sin(2.0 * math.pi * f_m * x[i]) / (2.0 * math.pi * f_m) 378 | ) 379 | 380 | return numpy.ndarray(time_assigned) 381 | 382 | 383 | @numba.jit 384 | def _time_assignment_new_to_old(y, a_m, f_m): 385 | time_assigned = y 386 | 387 | for k in range(1, 41): 388 | for i, elem in enumerate(y): 389 | time_assigned[i] = y[i] - a_m * math.sin( 390 | 2.0 * math.pi * f_m * time_assigned[i] 391 | ) / (2.0 * math.pi * f_m) 392 | 393 | return time_assigned 394 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | --------------------------------------------------------------------------------