U
    9%e,                     @   s   d dl Z d dlZd dlZddlmZmZmZmZmZm	Z	 ddl
mZ ddlmZmZ e jdkrbeZedd Zed(d
dZed)ddZed*ddZed+ddZed,ddZedd  Zed!d" Zed#d$ Zed-d&d'ZdS ).    N   )db_to_floatratio_to_dbregister_pydub_effectmake_chunksaudioopget_min_max_value)split_on_silence)TooManyMissingFramesInvalidDuration)   r   c           
         sn   | j }|  } fdd|D }|  }t|D ]2\}}t| D ]\}}|| | }	|||	< qDq0| |S )Nc                    s   g | ]} |qS  r   ).0channel_seg	filter_fnr   L/var/www/html/Darija-Ai-API/env/lib/python3.8/site-packages/pydub/effects.py
<listcomp>   s     z5apply_mono_filter_to_each_channel.<locals>.<listcomp>)channelssplit_to_monoget_array_of_samples	enumerate_spawn)
segr   Z
n_channelsZchannel_segsZout_dataZ	channel_ir   Zsample_isampleindexr   r   r   !apply_mono_filter_to_each_channel   s    r   皙?c                 C   s8   | j }|dkr| S | jt|  }t|| }| |S )za
    headroom is how close to the maximum volume to boost the signal up to (specified in dB)
    r   )maxmax_possible_amplituder   r   Z
apply_gain)r   ZheadroomZpeak_sample_valZtarget_peakZneeded_boostr   r   r   	normalize#   s    r          ?      c           	         s   d| }|dk r&t |d|  |  nt | t || d|  }t| d }t| |  }t|dk r~td||| j |8  |d } fdd|d d D }|d	 }|dd  D ]}|j||d
}q||7 }|S )N      ?       @r      zwCould not speed up AudioSegment, it was too short {2:0.2f}s for the current settings:
{0}ms chunks at {1:0.1f}x speedupc                    s   g | ]}|d    qS Nr   )r   chunkZms_to_remove_per_chunkr   r   r   W   s     zspeedup.<locals>.<listcomp>r   	crossfade)intminr   len	ExceptionformatZduration_secondsappend)	r   Zplayback_speed
chunk_sizer,   Zatkchunks
last_chunkoutr)   r   r*   r   speedup4   s*      r7     d   c                 C   sf   ||krt dt| |||}|d }t|s:| dd S |d } |dd  D ]}| j||d} qN| S )Nz)padding cannot be longer than silence_lenr&   r   r   r+   )r   r	   r/   r2   )r   Zsilence_lenZsilence_threshpaddingr4   r,   r)   r   r   r   strip_silencea   s    r<         4      @      @      I@c                    s  j t| tj|d  fdd}fdd}g }d}j|d}	j|d}
tt D ]}||}dd|  || }||	 }||
 }|kr||kr||7 }t||}n||8 }t|d	}|}|dkrt	|j
t| }|| qhjd
|dS )aL  
    Keyword Arguments:
        
        threshold - default: -20.0
            Threshold in dBFS. default of -20.0 means -20dB relative to the
            maximum possible volume. 0dBFS is the maximum possible value so
            all values for this argument sould be negative.

        ratio - default: 4.0
            Compression ratio. Audio louder than the threshold will be 
            reduced to 1/ratio the volume. A ratio of 4.0 is equivalent to
            a setting of 4:1 in a pro-audio compressor like the Waves C1.
        
        attack - default: 5.0
            Attack in milliseconds. How long it should take for the compressor
            to kick in once the audio has exceeded the threshold.

        release - default: 50.0
            Release in milliseconds. How long it should take for the compressor
            to stop compressing after the audio has falled below the threshold.

    
    For an overview of Dynamic Range Compression, and more detailed explanation
    of the related terminology, see: 

        http://en.wikipedia.org/wiki/Dynamic_range_compression
    )msc                    s    |   | jS r(   )Zget_sample_slicerms)Zframe_i)look_framesr   r   r   rms_at   s    z&compress_dynamic_range.<locals>.rms_atc                    s"   | dkrdS t |   }t|dS )Nr           )r   r   )rB   db)
thresh_rmsr   r   db_over_threshold   s     z1compress_dynamic_range.<locals>.db_over_thresholdrE   r   r$   r       data)r   r   r-   frame_countxranger.   r   Z	get_framer   mulsample_widthr2   r   join)r   	thresholdratioZattackreleaserD   rH   outputZattenuationZattack_framesZrelease_framesiZrms_nowZmax_attenuationZattenuation_incZattenuation_decframer   )rC   r   rG   r   compress_dynamic_ranges   s4    

rW   r   r   c                 C   s~   |dkr&t | j| jd}| j|dS | jdkr>|  \}}ntdt| j d |dkrf|	 }n|	 }| 
||S dS )	z
    channels- specifies which channel (left or right) to reverse the phase of.
    Note that mono AudioSegments will become stereo.
    rX         rJ   r&   z.Can't implicitly convert an AudioSegment with z channels to stereo.)r   r   N)r   rN   _datarO   r   r   r   r0   strinvert_phaseZfrom_mono_audiosegments)r   r   invertedleftrightr   r   r   r\      s    

r\   c                 C   s   d|d t j  }d| j }|||  }|  }t| j|}t|  }dg| j }t	| jD ]}	||	  ||	< ||	< q`t	d|D ]R}	t	| jD ]B}
|	| j |
 }||
 ||| ||
    ||
< t||
 ||< qq| j
|dS )z
        cutoff - Frequency (in Hz) where higher frequency signal will begin to
            be reduced by 6dB per octave (doubling in frequency) above this point
    r$   r&   r   r   rJ   )mathpi
frame_rater   array
array_typer-   rL   r   ranger   )r   cutoffRCdtalphaoriginalfilteredArrayrL   last_valrU   joffsetr   r   r   low_pass_filter   s    
 ro   c                 C   s  d|d t j  }d| j }|||  }t| jd \}}|  }t| j|}t| 	 }	dg| j
 }
t| j
D ]}||  |
|< ||< qrtd|	D ]p}t| j
D ]`}|| j
 | }|d | j
 | }||
| ||  ||   |
|< ttt|
| ||||< qq| j|dS )z
        cutoff - Frequency (in Hz) where lower frequency signal will begin to
            be reduced by 6dB per octave (doubling in frequency) below this point
    r$   r&      r   r   rJ   )r`   ra   rb   r   rO   r   rc   rd   r-   rL   r   re   r.   r   r   )r   rf   rg   rh   ri   minvalmaxvalrj   rk   rL   rl   rU   rm   rn   Zoffset_minus_1r   r   r   high_pass_filter   s"    
  rs   c                 C   sz   d|  krdksn t dtd}t|| }t|}t|| }t|}|d }|dk rj| ||S | ||S dS )as  
    pan_amount should be between -1.0 (100% left) and +1.0 (100% right)
    
    When pan_amount == 0.0 the left/right balance is not changed.
    
    Panning does not alter the *perceived* loundness, but since loudness
    is decreasing on one side, the other side needs to get louder to
    compensate. When panned hard left, the left channel will be 3dB louder.
    rY   r$   zCpan_amount should be between -1.0 (100% left) and +1.0 (100% right)r%   r   N)
ValueErrorr   absr   apply_gain_stereo)r   Z
pan_amountZmax_boost_dbZboost_dbZboost_factorZreduce_factorZ	reduce_dbr   r   r   pan  s    rw   rE   c           
      C   s   | j dkr|  }}n| j dkr*|  \}}t|}t|}t|j|j|}t||jdd}t|j|j|}t||jdd}t||| j}	| j	|	dd| j ddS )z
    left_gain - amount of gain to apply to the left channel (in dB)
    right_gain - amount of gain to apply to the right channel (in dB)
    
    note: mono audio segments will be converted to stereo
    r   r&   r   )r   Zframe_width)rK   Z	overrides)
r   r   r   r   rN   rZ   rO   Ztostereoaddr   )
r   Z	left_gainZ
right_gainr^   r_   Zl_mult_factorZr_mult_factorZ	left_dataZ
right_datarT   r   r   r   rv   ;  s     


rv   )r   )r!   r"   r#   )r8   r9   r:   )r=   r>   r?   r@   )rX   )rE   rE   )sysr`   rc   utilsr   r   r   r   r   r   Zsilencer	   
exceptionsr
   r   version_infore   rM   r   r    r7   r<   rW   r\   ro   rs   rw   rv   r   r   r   r   <module>   s6    

,L

 
