o
    i                     @   st   d dl Z d dlmZmZ d dlZdedeejejf fddZddd	d
ee	 de	dededee	e	f f
ddZ
dS )    N)OptionalTuplenum_samplesreturnc                 C   sj   | dkrt jdt jdt jdt jdfS t jdtjd | t jd}t j|t jd}t j|t jd}||fS )z
    Generate equal-power crossfade curves (cosine/sine) with length num_samples.
    Returns (fade_out, fade_in) as float32 arrays in range [0.0, 1.0].
    r   dtypeg        g       @)nponesfloat32linspacemathpicossin)r   anglesfade_outfade_in r   6/home/ubuntu/veenaModal/veena3modal/audio/crossfade.py_equal_power_fade_curves   s   r   i>  2   )sample_rate_hzcrossfade_msprevious_tailnew_audio_bytesr   r   c                C   s  |sd| pdfS d}t || d }|| }| s4t||kr"d|fS |d|  }|| d }||fS | }	t||k rt|t||  }
|
dkrPd|	| fS |
| }tj|	|
 d tjdtj}tj|d|
 tjdtj}t|\}}|| ||  tj }|	d|
  | }t||kr|| d n|}||fS tj|	tjdtj}tj|d| tjdtj}t|\}}|| ||  tj }t|d| kr|||  nd}|| }|| d }||fS )a  
    Perform equal-power crossfade between previous chunk tail and the start of a new chunk.
    Returns a tuple (to_emit, new_tail) where:
      - to_emit: bytes to stream now
      - new_tail: tail bytes to hold for the next iteration
    All audio is int16 PCM mono.
           i  Nr   r   )	intlenr   
frombufferint16astyper
   r   tobytes)r   r   r   r   bytes_per_samplecrossfade_samplescrossfade_bytesbodynew_tail	prev_tailoverlap_bytesoverlap_samplesprev_overlapnew_overlapr   r   
crossfadedemitnew_tail_candidatemiddleto_emitr   r   r   crossfade_bytes_int16   s@   "  "r2   )r   typingr   r   numpyr   r   ndarrayr   bytesr2   r   r   r   r   <module>   s"    
