o
    Si|                   	   @   s  d Z ddlZddlZddlZddlZddlZddlZddlm	Z	 ddl
mZmZmZ ddlmZmZ ejejdZ	dd	ed
ejdeje defddZddeje dejejef fddZdd	ed
ejdedefddZddedejejef fddZdd Zedkre  dS dS )z0API to compress/decompress audio to bytestreams.    N   )binary)ArithmeticCoderArithmeticDecoderbuild_stable_quantized_cdf)EncodecModelEncodedFrame)encodec_24khzencodec_48khzTmodelwavfouse_lmc              
   C   s  |  dks
J d| jtvrtd| j d|r|  }t  | |d }W d   n1 s4w   Y  | j|jd |d d jd |d	}t	
|| |D ]\}}|durh|td
|   |j\}	}
}|rt|}d}d}tjd|
dtj|jd}nt	| j|}t|D ]b}|rt  ||||\}}}W d   n1 sw   Y  d|dddd||d f  }t|ddd|f  D ]"\}}|rt|ddd|df |jdd}||| q|| qq|r|  qS|  qSdS )a  Compress a waveform to a file-object using the given model.

    Args:
        model (EncodecModel): a pre-trained EncodecModel to use to compress the audio.
        wav (torch.Tensor): waveform to compress, should have a shape `[C, T]`, with `C`
            matching `model.channels`, and the proper sample rate (e.g. `model.sample_rate`).
            Use `utils.convert_audio` if this is not the case.
        fo (IO[bytes]): file-object to which the compressed bits will be written.
            See `compress` if you want obtain a `bytes` object instead.
        use_lm (bool): if True, use a pre-trained language model to further
            compress the stream using Entropy Coding. This will slow down compression
            quite a bit, expect between 20 to 30% of size reduction.
       z$Only single waveform can be encoded.zThe provided model z is not supported.Nr   r   )malnclm!fdtypedeviceFcheck)dimnameMODELS
ValueErrorget_lm_modeltorchno_gradencodeshaper   write_ecdc_headerwritestructpackcpuitemr   zeroslongr   	BitPackerbits_per_codebookrange	enumeratetolistr   total_range_bitspushflush)r   r   r   r   r   framesmetadataframescale_KTcoderstatesoffsetinput_packertprobaskvalueq_cdf rE   D/home/ubuntu/.local/lib/python3.10/site-packages/encodec/compress.pycompress_to_file   sT   


""

rG   r(   returnc              
   C   s  t | }|d }|d }|d }|d }t|tsJ t|ts#J |tvr/td| dt|  |}|r=| }g }	|jpC|}
|j	pH|}t
d||D ]}t|| |
}tt||j |j }|jrtdt | td\}tj||d	d
}nd}|rt| }d}d}tjd
|d
tj|d}nt |j| }tjd
||tj|d}t
|D ]y}|rt  ||||\}}}W d   n1 sw   Y  g }t
|D ]+}|rt|ddd|df |jdd}| |}n|  }|du rt!d|"| qtj|tj|d}||ddd|f< |r(d
|dddd||d
 f  }q|	"||f qOt  |#|	}W d   n	1 sFw   Y  |dddd|f |jfS )a  Decompress from a file-object.
    Returns a tuple `(wav, sample_rate)`.

    Args:
        fo (IO[bytes]): file-object from which to read. If you want to decompress
            from `bytes` instead, see `decompress`.
        device: device to use to perform the computations.
    r   r   r   r   z3The audio was compressed with an unsupported model .r   r   r   r   Nr   Fr   z&The stream ended sooner than expected.)$r   read_ecdc_header
isinstanceintr   r   tor   segment_lengthsegment_strider.   minmathceilsample_rate
frame_rate	normalizer&   unpack_read_exactlycalcsizer    tensorviewr   r*   r+   BitUnpackerr-   r!   r   r1   pullEOFErrorappenddecode)r   r   r5   
model_nameaudio_lengthnum_codebooksr   r   r   r4   rO   rP   r=   this_segment_lengthframe_lengthscale_fr7   decoderr<   r>   unpackerr6   r@   rA   	code_listrB   rD   codecodesr   rE   rE   rF   decompress_from_file\   sn   
	


"
rl   Fc                 C   s    t  }t| |||d | S )a  Compress a waveform using the given model. Returns the compressed bytes.

    Args:
        model (EncodecModel): a pre-trained EncodecModel to use to compress the audio.
        wav (torch.Tensor): waveform to compress, should have a shape `[C, T]`, with `C`
            matching `model.channels`, and the proper sample rate (e.g. `model.sample_rate`).
            Use `utils.convert_audio` if this is not the case.
        use_lm (bool): if True, use a pre-trained language model to further
            compress the stream using Entropy Coding. This will slow down compression
            quite a bit, expect between 20 to 30% of size reduction.
    r   )ioBytesIOrG   getvalue)r   r   r   r   rE   rE   rF   compress   s   rq   
compressedc                 C   s   t | }t||dS )zDecompress from a file-object.
    Returns a tuple `(wav, sample_rate)`.

    Args:
        compressed (bytes): compressed bytes.
        device: device to use to perform the computations.
    rJ   )rn   ro   rl   )rr   r   r   rE   rE   rF   
decompress   s   
rs   c               
   C   s   dd l } td t D ]}t|  }|jd }| d| d\}}|d d d |jd f }|d dD ]T}td	| d
|  t		 }t
|||d}t		 | }	t|\}
}t		 | |	 }dt| d |jd |j  }td|dd|	dd|dd |
j|jksJ q8qd S )Nr   r   i  test_zk.wav      )FTzDoing z	, use_lm=rm      r   zkbps: z.1fz, time comp: z sec. time decomp:rI   )
torchaudior    set_num_threadsr   keysrT   loadset_target_bandwidthprinttimerq   rs   lenr#   )rx   r   r   srxr8   r   beginrest_compx_dect_decompkbpsrE   rE   rF   test   s,   



 
r   __main__)T)r(   )F) __doc__rn   rR   r&   r~   typingtpr     r   quantization.acr   r   r   r   r   r   encodec_model_24khzencodec_model_48khzr   TensorIObytesboolrG   TuplerM   rl   rq   rs   r   __name__rE   rE   rE   rF   <module>   s0   
&@C 
