B
    ²}ú]O8  ã               @   s¾   d Z ddlmZmZmZ ddlZddlZddlZddlZdddgZ	G dd„ de
ƒZdZd	Zd
ZeefZdd„ Zddd„Zdd„ Zdd„ Zddd„Zdd„ Zejd d	kr²dd„ Zndd„ ZdS )zÂ
Module to read / write wav files using numpy arrays

Functions
---------
`read`: Return the sample rate (in samples/sec) and data from a WAV file.

`write`: Write a numpy array as a WAV file.

é    )ÚdivisionÚprint_functionÚabsolute_importNÚWavFileWarningÚreadÚwritec               @   s   e Zd ZdS )r   N)Ú__name__Ú
__module__Ú__qualname__© r   r   ú\/home/fristb/BIRCH/lib-linux-x86_64/python/lib64/python3.7/site-packages/scipy/io/wavfile.pyr      s   é   é   iþÿ  c             C   sH  |r
d}nd}t  |d |  d¡¡d  }}d}|dk r@tdƒ‚t  |d |  d¡¡}|d7 }|\}}}}	}
}|tkr|d	krt  |d
 |  d¡¡d }|d7 }|dkr|  d¡}|d7 }|dd… }|rÖd}nd}| |¡rt  |d |dd… ¡d }ntdƒ‚|tkrtdƒ‚||kr6|  || ¡ |||||	|
|fS )aÔ  
    Returns
    -------
    size : int
        size of format subchunk in bytes (minus 8 for "fmt " and itself)
    format_tag : int
        PCM, float, or compressed format
    channels : int
        number of channels
    fs : int
        sampling frequency in samples per second
    bytes_per_second : int
        overall byte rate for the file
    block_align : int
        bytes per sample, including all channels
    bit_depth : int
        bits per sample
    ú>ú<ÚIé   r   é   z.Binary structure of wave file is not compliantZHHIIHHé   ÚHé   é   é   s      €  ª 8›qs      €  ª 8›qNzUnknown wave file format)ÚstructÚunpackr   Ú
ValueErrorÚWAVE_FORMAT_EXTENSIBLEÚendswithÚKNOWN_WAVE_FORMATS)ÚfidÚis_big_endianÚfmtÚsizeÚresZ
bytes_readÚ
format_tagÚchannelsÚfsÚbytes_per_secondÚblock_alignÚ	bit_depthZext_chunk_sizeZextensible_chunk_dataZraw_guidÚtailr   r   r   Ú_read_fmt_chunk'   s:    



r+   Fc             C   sÌ   |r
d}nd}t  ||  d¡¡d }|d }|dkr:d}	n0|rDd}	nd}	|tkr^|	d	| 7 }	n|	d
| 7 }	|s„tj|  |¡|	d}
n0|  ¡ }tj| |	d||| fd}
|  || ¡ |dkrÈ|
 	d|¡}
|
S )Nz>Iz<Ir   r   é   Úu1r   r   zi%dzf%d)ÚdtypeÚc)r.   ÚmodeÚoffsetÚshaper   éÿÿÿÿ)
r   r   r   ÚWAVE_FORMAT_PCMÚnumpyÚ
frombufferÚtellÚmemmapÚseekÚreshape)r   r$   r%   r)   r    Úmmapr!   r"   Zbytes_per_sampler.   ÚdataÚstartr   r   r   Ú_read_data_chunki   s,    r>   c             C   s<   |r
d}nd}|   d¡}|r8t ||¡d }|  |d¡ d S )Nz>Iz<Ir   r   r   )r   r   r   r9   )r   r    r!   r<   r"   r   r   r   Ú_skip_unknown_chunk   s    
r?   c             C   s|   |   d¡}|dkrd}d}n$|dkr.d}d}ntd t|ƒ¡ƒ‚t ||   d¡¡d	 d
 }|   d¡}|dkrttdƒ‚||fS )Nr   s   RIFFFz<Is   RIFXTz>Iz!File format {}... not understood.r   r,   s   WAVEzNot a WAV file.)r   r   ÚformatÚreprr   r   )r   Zstr1r    r!   Ú	file_sizeZstr2r   r   r   Ú_read_riff_chunk   s    

rC   c          	   C   sª  t | dƒr| }d}n
t| dƒ}z^t|ƒ\}}d}d}d}d}t}	x6| ¡ |k rz| d¡}
|
s|r†tjd | ¡ |¡t	dd	 P q¤t
d
ƒ‚nt|
ƒdk r¤t
dƒ‚|
dkrìd}t||ƒ}|dd… \}	}}|d }|dkrêt
d |¡ƒ‚qF|
dkrt||ƒ qF|
dkr2d}|st
dƒ‚t||	||||ƒ}qF|
dkrHt||ƒ qF|
dkr^t||ƒ qFtjdt	dd	 t||ƒ qFW W dt | dƒs–| ¡  n
| d¡ X ||fS )a„	  
    Open a WAV file

    Return the sample rate (in samples/sec) and data from a WAV file.

    Parameters
    ----------
    filename : string or open file handle
        Input wav file.
    mmap : bool, optional
        Whether to read data as memory-mapped.
        Only to be used on real files (Default: False).

        .. versionadded:: 0.12.0

    Returns
    -------
    rate : int
        Sample rate of wav file.
    data : numpy array
        Data read from wav file.  Data-type is determined from the file;
        see Notes.

    Notes
    -----
    This function cannot read wav files with 24-bit data.

    Common data types: [1]_

    =====================  ===========  ===========  =============
         WAV format            Min          Max       NumPy dtype
    =====================  ===========  ===========  =============
    32-bit floating-point  -1.0         +1.0         float32
    32-bit PCM             -2147483648  +2147483647  int32
    16-bit PCM             -32768       +32767       int16
    8-bit PCM              0            255          uint8
    =====================  ===========  ===========  =============

    Note that 8-bit PCM is unsigned.

    References
    ----------
    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
       Interface and Data Specifications 1.0", section "Data Format of the
       Samples", August 1991
       http://www.tactilemedia.com/info/MCI_Control_Info.html

    Examples
    --------
    >>> from os.path import dirname, join as pjoin
    >>> import scipy.io as sio

    Get the filename for an example .wav file from the tests/data directory.

    >>> data_dir = pjoin(dirname(sio.__file__), 'tests', 'data')
    >>> wav_fname = pjoin(data_dir, 'test-44100Hz-2ch-32bit-float-be.wav')

    Load the .wav file contents.

    >>> samplerate, data = sio.wavfile.read(wav_fname)
    >>> print(f"number of channels = {data.shape[1]}")
    number of channels = 2
    >>> length = data.shape[0] / samplerate
    >>> print(f"length = {length}s")
    length = 0.01s

    Plot the waveform.

    >>> import matplotlib.pyplot as plt
    >>> import numpy as np
    >>> time = np.linspace(0., length, data.shape[0])
    >>> plt.plot(time, data[:, 0], label="Left channel")
    >>> plt.plot(time, data[:, 1], label="Right channel")
    >>> plt.legend()
    >>> plt.xlabel("Time [s]")
    >>> plt.ylabel("Amplitude")
    >>> plt.show()

    r   FÚrbr   r,   r   zQReached EOF prematurely; finished at {:d} bytes, expected {:d} bytes from header.r   )Ú
stacklevelzUnexpected end of file.zIncomplete wav chunk.s   fmt Tr   )r,   r   é    é@   é`   é€   z4Unsupported bit depth: the wav file has {}-bit data.s   facts   datazNo fmt chunk before datas   LIST)s   JUNKs   Fakez-Chunk (non-data) not understood, skipping it.Nr   )ÚhasattrÚopenrC   r4   r7   r   ÚwarningsÚwarnr@   r   r   Úlenr+   r?   r>   Úcloser9   )Úfilenamer;   r   rB   r    Zfmt_chunk_receivedZdata_chunk_receivedr%   r)   r$   Zchunk_idZ	fmt_chunkr&   r<   r   r   r   r   ´   sd    P















c          	   C   s2  t | dƒr| }n
t| dƒ}|}zê|jj}|dks\|dks\|dkrN|jjdks\td|j ƒ‚d}|d	7 }|d
7 }|d7 }|d7 }|dkrŽt}nt}|jdkr¢d}n
|j	d }|jjd }	||	d  | }
||	d  }t
 d||||
||	¡}|dks|dks|d7 }|t
 dt|ƒ¡7 }||7 }|dksV|dksV|d7 }|t
 dd|j	d ¡7 }t|ƒd d d|j  dkr~tdƒ‚| |¡ | d¡ | t
 d|j¡¡ |jjdksÎ|jjdkrÖtjdkrÖ| ¡ }t||ƒ | ¡ }| d¡ | t
 d|d ¡¡ W dt | dƒs"| ¡  n
| d¡ X dS )aÓ  
    Write a numpy array as a WAV file.

    Parameters
    ----------
    filename : string or open file handle
        Output wav file.
    rate : int
        The sample rate (in samples/sec).
    data : ndarray
        A 1-D or 2-D numpy array of either integer or float data-type.

    Notes
    -----
    * Writes a simple uncompressed WAV file.
    * To write multiple-channels, use a 2-D array of shape
      (Nsamples, Nchannels).
    * The bits-per-sample and PCM/float will be determined by the data-type.

    Common data types: [1]_

    =====================  ===========  ===========  =============
         WAV format            Min          Max       NumPy dtype
    =====================  ===========  ===========  =============
    32-bit floating-point  -1.0         +1.0         float32
    32-bit PCM             -2147483648  +2147483647  int32
    16-bit PCM             -32768       +32767       int16
    8-bit PCM              0            255          uint8
    =====================  ===========  ===========  =============

    Note that 8-bit PCM is unsigned.

    References
    ----------
    .. [1] IBM Corporation and Microsoft Corporation, "Multimedia Programming
       Interface and Data Specifications 1.0", section "Data Format of the
       Samples", August 1991
       http://www.tactilemedia.com/info/MCI_Control_Info.html

    Examples
    --------
    Create a 100Hz sine wave, sampled at 44100Hz.
    Write to 16-bit PCM, Mono.

    >>> from scipy.io.wavfile import write
    >>> samplerate = 44100; fs = 100
    >>> t = np.linspace(0., 1., samplerate)
    >>> amplitude = np.iinfo(np.int16).max
    >>> data = amplitude * np.sin(2. * np.pi * fs * t)
    >>> write("example.wav", samplerate, data)

    r   ÚwbÚiÚfÚur   zUnsupported data type '%s'ó    s   RIFFs       s   WAVEs   fmt r,   z<HHIIHHs     z<Is   factz<IIr   r   l   ÿÿ z!Data exceeds wave file size limits   datar   ú=ÚbigN)rJ   rK   r.   ÚkindÚitemsizer   ÚWAVE_FORMAT_IEEE_FLOATr4   Úndimr2   r   ÚpackrN   Únbytesr   Ú	byteorderÚsysÚbyteswapÚ_array_tofiler7   r9   rO   )rP   Úrater<   r   r&   ZdkindZheader_datar$   r%   r)   r'   r(   Zfmt_chunk_datar"   r   r   r   r   F  s^    5




 




c             C   s   |   | ¡  d¡j¡ d S )NÚb)r   ÚravelÚviewr<   )r   r<   r   r   r   ra   Æ  s    ra   c             C   s   |   | ¡ ¡ d S )N)r   Útostring)r   r<   r   r   r   ra   Ê  s    )F)F)Ú__doc__Ú
__future__r   r   r   r_   r5   r   rL   Ú__all__ÚUserWarningr   r4   rZ   r   r   r+   r>   r?   rC   r   r   Úversion_infora   r   r   r   r   Ú<module>
   s.   C
#
 
