o
    rri%                     @   s  d dl Z d dlZd dlm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 ZG dd dZd*d
dZdd Zdd Zdd Zdd Zd+ddZd,ddZ						d-de	jdejeef ded ed!ejd" d#ejd$ d%ed&ejd' fd(d)ZdS ).    N)Path   )temp_filenamesc              
   C   s.   t dddt| ddddg}t|dS )	Nffprobe	-loglevelpanicz-print_formatjsonz-show_formatz-show_streamszutf-8)spcheck_outputstrr   loadsdecode)pathstdout_data r   @/home/ubuntu/.local/lib/python3.10/site-packages/demucs/audio.py
_read_info   s
   r   c                   @   s~   e Zd ZdZdefddZdd Zedd Zed	d
 Z	edd Z
dd ZdddZdddZddedddfddZdS )	AudioFilez
    Allows to read audio from any format supported by ffmpeg, as well as resampling or
    converting to mono on the fly. See :method:`read` for more details.
    r   c                 C   s   t || _d | _d S N)r   r   _info)selfr   r   r   r   __init__!   s   

zAudioFile.__init__c                 C   sb   d| j fg}|d|  f |d|  f |dt| f ddd |D }d| d	S )
Nr   
sampleratechannelsstreamsz, c                 s   s"    | ]\}}| d | V  qdS )=Nr   ).0namevaluer   r   r   	<genexpr>*   s     z%AudioFile.__repr__.<locals>.<genexpr>z
AudioFile())r   appendr   r   lenjoin)r   featuresfeatures_strr   r   r   __repr__%   s   zAudioFile.__repr__c                 C   s   | j d u rt| j| _ | j S r   )r   r   r   r   r   r   r   info-   s   
zAudioFile.infoc                 C   s   t | jd d S )Nformatduration)floatr(   r'   r   r   r   r*   3   s   zAudioFile.durationc                 C   s   dd t | jd D S )Nc                 S   s    g | ]\}}|d  dkr|qS )
codec_typeaudior   )r   indexstreamr   r   r   
<listcomp>9   s
    z,AudioFile._audio_streams.<locals>.<listcomp>r   )	enumerater(   r'   r   r   r   _audio_streams7   s   zAudioFile._audio_streamsc                 C   s
   t | jS r   )r"   r2   r'   r   r   r   __len__>   s   
zAudioFile.__len__r   c                 C      t | jd | j|  d S )Nr   r   intr(   r2   r   r/   r   r   r   r   A      zAudioFile.channelsc                 C   r4   )Nr   sample_rater5   r7   r   r   r   r   D   r8   zAudioFile.samplerateNc                 C   s  t tt| | }t|t j }|r|g}|du r d}d}nt|p&|  | }t|d |p3|   }t	t|}	ddg}
|
ddg7 }
|rQ|
dt
|g7 }
|
dt
| jg7 }
t||	D ]9\}}|
d	d
| j|  g7 }
|dur{|
dt
|g7 }
|
ddg7 }
|
ddg7 }
|dur|
dt
|g7 }
|
|g7 }
q_tj|
dd g }|	D ]3}t j|t jd}t|}|d|   }|durt||}|dur|dd|f }|| qW d   n1 sw   Y  tj|dd}|r|d }|S )a,  
        Slightly more efficient implementation than stempeg,
        in particular, this will extract all stems at once
        rather than having to loop over one file multiple times
        for each stream.

        Args:
            seek_time (float):  seek time in seconds or None if no seeking is needed.
            duration (float): duration in seconds to extract or None to extract until the end.
            streams (slice, int or list): streams to extract, can be a single int, a list or
                a slice. If it is a slice or list, the output will be of size [S, C, T]
                with S the number of streams, C the number of channels and T the number of samples.
                If it is an int, the output will be [C, T].
            samplerate (int): if provided, will resample on the fly. If None, no resampling will
                be done. Original sampling rate can be obtained with :method:`samplerate`.
            channels (int): if 1, will convert to mono. We do not rely on ffmpeg for that
                as ffmpeg automatically scale by +3dB to conserve volume when playing on speakers.
                See https://sound.stackexchange.com/a/42710.
                Our definition of mono is simply the average of the two channels. Any other
                value will be ignored.
        Nr   ffmpegz-yr   r   z-ssz-iz-mapz0:z-tz-threads1z-ff32lez-arT)check)dtype.r   )dim)nparrayranger"   
isinstancendarrayr6   r   r+   r   r   r   zipr2   r	   runfromfilefloat32torch
from_numpyviewr   tconvert_audio_channelsr!   stack)r   	seek_timer*   r   r   r   singletarget_sizequery_duration	filenamescommandr/   filenamewavswavr   r   r   readG   sR   

zAudioFile.read)r   )__name__
__module____qualname____doc__r   r   r&   propertyr(   r*   r2   r3   r   r   slicerY   r   r   r   r   r      s&    




r      c                 C   s   | j ^ }}}||kr	 | S |dkr| jddd} | S |dkr-| jg |||R  } | S ||kr>| dd|ddf } | S td)z.Convert audio to the given number of channels.r   T)r@   keepdim.Nz@The audio file has less channels than requested but is not mono.)shapemeanexpand
ValueError)rX   r   rc   src_channelslengthr   r   r   rN      s   	rN   c                 C   s   t | |} t| ||S )zTConvert audio from a given samplerate to a target one and target number of channels.)rN   juliusresample_frac)rX   from_samplerateto_samplerater   r   r   r   convert_audio   s   
rm   c                 C   s    | j jr| ddd  S | S )z,Convert audio to 16 bits integer PCM format.r?   r     )r>   is_floating_pointclamp_shortrX   r   r   r   i16_pcm   s   rs   c                 C   s   | j jr| S |  d S )z*Convert audio to float 32 bits PCM format.rn   )r>   ro   r+   rr   r   r   r   f32_pcm   s   rt   c                 C   s   | j jrt| S t| S )zHConvert audio to either f32 pcm or i16 pcm depending on the given dtype.)r>   ro   rt   rs   )rX   r>   r   r   r   as_dtype_pcm   s   ru   D  @  Fc                 C   s   | j \}}t| } t }|| || || || |s'|  | j	
 } | dd } ||  }	|	| 7 }	t|d}
|
|	 W d   dS 1 sWw   Y  dS )z6Save given audio as mp3. This should work on all OSes.r   r   wbN)rc   rs   lameencEncoderset_bit_rateset_in_sample_rateset_channelsset_qualitysilencedatacpu	transposenumpyencodetobytesflushopenwrite)rX   r   r   bitratequalityverboseCTencodermp3_datafr   r   r   
encode_mp3   s    





"r   rescalec                 C   s   |du s|dkr
| S | j jsJ d|dkr%| td|    d } | S |dkr1| dd	} | S |d
kr<t| } | S td| )z9
    different strategies for avoiding raw clipping.
    Nnoneztoo late for clippingr   g)\(?r   clampgGzgGz?tanhzInvalid mode )r>   ro   maxabsr   rJ   r   rf   )rX   moder   r   r   prevent_clip   s   
r      rX   r   r   r   clip)r   r   r   r   bits_per_sample)r          as_floatpreset)r`                  c           
      C   s   t | |d} t|}|j }|dkrt| ||||dd dS |dkr:|r*d}d}	nd}	tjt|| ||	|d	 dS |d
krKtjt|| ||d dS td| )a  Save audio file, automatically preventing clipping if necessary
    based on the given `clip` strategy. If the path ends in `.mp3`, this
    will save as mp3 with the given `bitrate`. Use `preset` to set mp3 quality:
    2 for highest quality, 7 for fastest speed
    )r   z.mp3T)r   z.wavr   PCM_FPCM_S)r9   encodingr   z.flac)r9   r   zInvalid suffix for path: N)	r   r   suffixlowerr   tasaver   rf   )
rX   r   r   r   r   r   r   r   r   r   r   r   r   
save_audio   s    

r   )r`   )rv   rw   r`   F)r   )rw   r   r   Fr`   ) r   
subprocessr	   pathlibr   ry   ri   r   rA   rJ   
torchaudior   typingtputilsr   r   r   rN   rm   rs   rt   ru   r   r   TensorUnionr   r6   Literalboolr   r   r   r   r   <module>   sN   
s


