
    mi%                     Z   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 Z G d d      ZddZd	 Zd
 Zd Zd ZddZddZ	 	 	 	 	 dde	j2                  dej4                  eef   dededej:                  d   dej:                  d   dedej:                  d   fdZy)    N)Path   )temp_filenamesc           
          t        j                  dddt        |       ddddg      }t        j                  |j                  d            S )	Nffprobe	-loglevelpanicz-print_formatjsonz-show_formatz-show_streamszutf-8)spcheck_outputstrr
   loadsdecode)pathstdout_datas     F/var/www/stems/demucs_env/lib/python3.12/site-packages/demucs/audio.py
_read_infor      sG    //;D	?FNO# K ::k((122    c                       e Zd ZdZdefdZd Zed        Zed        Z	ed        Z
d Zdd	Zdd
Zdd ed      ddfdZy)	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                 2    t        |      | _        d | _        y N)r   r   _info)selfr   s     r   __init__zAudioFile.__init__!   s    J	
r   c                    d| j                   fg}|j                  d| j                         f       |j                  d| j                         f       |j                  dt	        |       f       dj                  d |D              }d| dS )	Nr   
sampleratechannelsstreamsz, c              3   0   K   | ]  \  }}| d |   yw)=N ).0namevalues      r   	<genexpr>z%AudioFile.__repr__.<locals>.<genexpr>*   s      O{tUD65'!2 Os   z
AudioFile())r   appendr   r   lenjoin)r   featuresfeatures_strs      r   __repr__zAudioFile.__repr__%   sz    TYY'(t'89:T]]_56CI./yy Oh OOL>++r   c                 f    | j                   t        | j                        | _         | j                   S r   )r   r   r   r   s    r   infozAudioFile.info-   s&    ::#DII.DJzzr   c                 8    t        | j                  d   d         S )Nformatduration)floatr0   r/   s    r   r3   zAudioFile.duration3   s    TYYx(455r   c                 t    t        | j                  d         D cg c]  \  }}|d   dk(  r| c}}S c c}}w )Nr   
codec_typeaudio)	enumerater0   )r   indexstreams      r   _audio_streamszAudioFile._audio_streams7   sC     (191E'F
#eVl#w. 
 	
 
s   4c                 ,    t        | j                        S r   )r)   r;   r/   s    r   __len__zAudioFile.__len__>   s    4&&''r   c                 X    t        | j                  d   | j                  |      d         S )Nr   r   intr0   r;   r   r:   s     r   r   zAudioFile.channelsA   s+    499Y'(;(;F(CDZPQQr   c                 X    t        | j                  d   | j                  |      d         S )Nr   sample_rater?   rA   s     r   r   zAudioFile.samplerateD   s+    499Y'(;(;F(CD]STTr   Nc                 V   t        j                  t        t        |                   |   }t	        |t         j
                         }|r|g}|d}d}nCt        |xs | j                         |z        }t        |dz   |xs | j                         z        }t        t        |            5 }	ddg}
|
ddgz  }
|r|
dt        |      gz  }
|
dt        | j                        gz  }
t        ||	      D ]T  \  }}|
d	d
| j                  |    gz  }
||
dt        |      gz  }
|
ddgz  }
|
ddgz  }
||
dt        |      gz  }
|
|gz  }
V t        j                  |
d       g }|	D ]  }t        j                   |t         j"                        }t%        j&                  |      }|j)                  d| j+                               j-                         }|t/        ||      }|	|dd|f   }|j1                  |        	 ddd       t%        j2                  d      }|r|d   }|S # 1 sw Y   )xY w)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ndarrayr@   r   r4   r   r   r   zipr;   r   runfromfilefloat32torch
from_numpyviewr   tconvert_audio_channelsr(   stack)r   	seek_timer3   r   r   r   singletarget_sizequery_duration	filenamescommandr:   filenamewavswavs                  r   readzAudioFile.readG   sJ   6 ((5T+,W544iGK!Nz>T__->(JKK"K!O
8WdooFW#XYNCL) 	!Y&GW--GE3y>22c$))n--G$'$; & Fb)<)<V)D(E$FGG!-c.&9::GJ,,D'?*)s:77GH:%& FF7$'D% !kk("**=&&s+hhr4==?3557'0h?C*c<K</0CC !%	!6 kk$A&a&C
=	! 	!s   )EHH()r   )__name__
__module____qualname____doc__r   r   r-   propertyr0   r3   r;   r=   r   r   slicerd   r"   r   r   r   r      s    T ,  
 6 6 
 
(RU 4[Er   r   c                     | j                   ^ }}}||k(  r	 | S |dk(  r| j                  dd      } | S |dk(  r | j                  g ||| } | S ||k\  r| dd|ddf   } | S t        d      )z.Convert audio to the given number of channels.r   T)rK   keepdim.Nz@The audio file has less channels than requested but is not mono.)shapemeanexpand
ValueError)rc   r   rn   src_channelslengths        r   rY   rY      s    #&99 UL&x& J% 
Q hh2th, J 
	 cjj2%2262 J 
	! #yy!#$ J [\\r   c                 H    t        | |      } t        j                  | ||      S )zTConvert audio from a given samplerate to a target one and target number of channels.)rY   juliusresample_frac)rc   from_samplerateto_samplerater   s       r   convert_audiory      s#    
 h
/C_mDDr   c                 x    | j                   j                  r#| j                  dd      dz  j                         S | S )z,Convert audio to 16 bits integer PCM format.rJ   r     )rI   is_floating_pointclamp_shortrc   s    r   i16_pcmr      s3    
yy""

2q!Y/6688
r   c                 X    | j                   j                  r| S | j                         dz  S )z*Convert audio to float 32 bits PCM format.r{   )rI   r|   r4   r   s    r   f32_pcmr      s%    
yy""
yy{i((r   c                 Z    | j                   j                  rt        |       S t        |       S )zHConvert audio to either f32 pcm or i16 pcm depending on the given dtype.)rI   r|   r   r   )rc   rI   s     r   as_dtype_pcmr      s#    
yy""s|s|r   c                 H   | j                   \  }}t        |       } t        j                         }|j	                  |       |j                  |       |j                  |       |j                  |       |s|j                          | j                  j                         } | j                  dd      j                         } |j                  | j                               }	|	|j                         z  }	t!        |d      5 }
|
j#                  |	       ddd       y# 1 sw Y   yxY w)z6Save given audio as mp3. This should work on all OSes.r   r   wbN)rn   r   lameencEncoderset_bit_rateset_in_sample_rateset_channelsset_qualitysilencedatacpu	transposenumpyencodetobytesflushopenwrite)rc   r   r   bitratequalityverboseCTencodermp3_datafs              r   
encode_mp3r      s    99DAq
#,CooG!z* 
((,,.C
--1

#
#
%C~~ckkm,HH	dD	 Q	  s   =DD!c                 >   ||dk(  r| S | j                   j                  sJ d       |dk(  r0| t        d| j                         j                         z  d      z  } | S |dk(  r| j	                  dd      } | S |d	k(  rt        j                  |       } | S t        d
|       )z9
    different strategies for avoiding raw clipping.
    noneztoo late for clippingrescaleg)\(?r   clampgGzgGz?tanhzInvalid mode )rI   r|   maxabsr   rU   r   rq   )rc   modes     r   prevent_clipr      s     |tv~
99&&?(??&yCswwy}}.22 J 
iit$
 J	 
jjo J =/00r   rc   r   r   r   clip)r   r   r   r   bits_per_sample)          as_floatpreset)                  c                 d   t        | |      } t        |      }|j                  j                         }|dk(  rt	        | ||||d       y|dk(  r-|rd}d}	nd}	t        j                  t        |      | ||	|	       y|d
k(  r#t        j                  t        |      | ||       y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)rC   encodingr   z.flac)rC   r   zInvalid suffix for path: N)	r   r   suffixlowerr   tasaver   rq   )
rc   r   r   r   r   r   r   r   r   r   s
             r   
save_audior      s     s
&C:D[[ F3j'64H	6	 OHH
D	3J!?	D	7	
D	3JX4VH=>>r   )r   )iD  @  r   F)r   )r   r   r   Fr   ) r
   
subprocessr   pathlibr   r   ru   r   rL   rU   
torchaudior   typingtputilsr   r   r   rY   ry   r   r   r   r   r   TensorUnionr   r@   Literalboolr   r"   r   r   <module>r      s             !3p pf4E)&* "FO9; %67?ELL ?XXc4i(?? ? ZZ BC	?
 !#

: 6? ? zz"23?r   