Skip to content

Commit

Permalink
Switch on SFC_SET_CLIPPING in SoundFile.__init__()
Browse files Browse the repository at this point in the history
See #104.
Incidentally, this closes #20.
  • Loading branch information
mgeier committed Feb 28, 2015
1 parent a75b0dc commit 7724a09
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
4 changes: 4 additions & 0 deletions pysoundfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
SFC_GET_FORMAT_MAJOR = 0x1031,
SFC_GET_FORMAT_SUBTYPE_COUNT = 0x1032,
SFC_GET_FORMAT_SUBTYPE = 0x1033,
SFC_SET_CLIPPING = 0x10C0,
} ;
enum
Expand Down Expand Up @@ -690,6 +691,9 @@ def __init__(self, file, mode='r', samplerate=None, channels=None,
# Move write position to 0 (like in Python file objects)
self.seek(0)

_snd.sf_command(self._file, _snd.SFC_SET_CLIPPING, _ffi.NULL,
_snd.SF_TRUE)

name = property(lambda self: self._name)
"""The file name of the sound file."""
mode = property(lambda self: self._mode)
Expand Down
34 changes: 34 additions & 0 deletions tests/test_pysoundfile.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import pysoundfile as sf
import numpy as np
import os
import io
import shutil
import pytest

Expand Down Expand Up @@ -74,6 +75,12 @@ def file_wplus(request):
return _file_new(request, os.O_CREAT | os.O_RDWR, 'w+b')


@pytest.yield_fixture
def file_inmemory():
with io.BytesIO() as f:
yield f


@pytest.yield_fixture
def sf_stereo_r(file_stereo_r):
with sf.SoundFile(file_stereo_r) as f:
Expand Down Expand Up @@ -423,6 +430,33 @@ def test_if_open_with_mode_w_truncates(file_stereo_rplus, mode):
pass


def test_clipping_float_to_int(file_inmemory):
float_to_clipped_int16 = [
(-1.0 - 2**-15, -2**15 ),
(-1.0 , -2**15 ),
(-1.0 + 2**-15, -2**15 + 1),
( 0.0 , 0 ),
( 1.0 - 2**-14, 2**15 - 2),
( 1.0 - 2**-15, 2**15 - 1),
( 1.0 , 2**15 - 1),
]
written, expected = zip(*float_to_clipped_int16)
sf.write(written, file_inmemory, 44100, format='WAV', subtype='PCM_16')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False, dtype='int16')
assert np.all(read == expected)
assert fs == 44100


def test_non_clipping_float_to_float(file_inmemory):
data = -2.0, -1.0, 0.0, 1.0, 2.0
sf.write(data, file_inmemory, 44100, format='WAV', subtype='FLOAT')
file_inmemory.seek(0)
read, fs = sf.read(file_inmemory, always_2d=False)
assert np.all(read == data)
assert fs == 44100


# -----------------------------------------------------------------------------
# Test file metadata
# -----------------------------------------------------------------------------
Expand Down

0 comments on commit 7724a09

Please sign in to comment.