o
    i!                     @   sR   d dl Z ddlmZ ddlmZ ddlmZmZ d dl	m
Z
mZ G dd dZdS )	    N   )	FfiHandle)audio_frame_pb2)_ensure_compatible_bufferget_address)AnyUnionc                   @   s:  e Zd ZdZdddeeeef dedededee	e
ef df d	dfd
dZedededed	d fddZedejd	d fddZd	ejfddZed	e	e
ef fddZed	efddZed	efddZed	efddZed	efddZed	efddZd	efdd Zd	e
fd!d"Zed#efd$d%ZdS )&
AudioFramez
    A class that represents a frame of audio data with specific properties such as sample rate,
    number of channels, and samples per channel.

    The format of the audio data is 16-bit signed integers (int16) interleaved by channel.
    N)userdatadatasample_ratenum_channelssamples_per_channelr
   returnc                C   s   t |tr
|d}t|}|| ttj }t|}||k r$td|ttj dkr2td|| _	|| _
|| _|| _|du rGi | _dS || _dS )aG  
        Initialize an AudioFrame instance.

        Args:
            data (Union[bytes, bytearray, memoryview]): The raw audio data, which must be at least
                `num_channels * samples_per_channel * sizeof(int16)` bytes long.
            sample_rate (int): The sample rate of the audio in Hz.
            num_channels (int): The number of audio channels (e.g., 1 for mono, 2 for stereo).
            samples_per_channel (int): The number of samples per channel.

        Raises:
            ValueError: If the length of `data` is smaller than the required size.
        BzIdata length must be >= num_channels * samples_per_channel * sizeof(int16)r   z/data length must be a multiple of sizeof(int16)N)
isinstance
memoryviewcastr   ctypessizeofc_int16len
ValueError_data_sample_rate_num_channels_samples_per_channel	_userdata)selfr   r   r   r   r
   min_sizedata_len r!   Y/var/www/html/livekit_bhavya/venv/lib/python3.10/site-packages/livekit/rtc/audio_frame.py__init__   s    

zAudioFrame.__init__c                 C   s*   || t t j }t|}t|| ||S )a  
        Create a new empty AudioFrame instance with specified sample rate, number of channels,
        and samples per channel.

        Args:
            sample_rate (int): The sample rate of the audio in Hz.
            num_channels (int): The number of audio channels (e.g., 1 for mono, 2 for stereo).
            samples_per_channel (int): The number of samples per channel.

        Returns:
            AudioFrame: A new AudioFrame instance with uninitialized (zeroed) data.
        )r   r   r   	bytearrayr	   )r   r   r   sizer   r!   r!   r"   createL   s   zAudioFrame.create
owned_infoc                 C   sP   | j }|j|j }tj| |j}t|}t| j	j
  t||j|j|jS N)infor   r   r   r   from_addressdata_ptrr$   r   handleiddisposer	   r   )r'   r)   r%   cdatar   r!   r!   r"   _from_owned_info^   s   zAudioFrame._from_owned_infoc                 C   s0   t  }t| j|_| j|_| j|_| j|_|S r(   )proto_audioAudioFrameBufferInfor   r   r+   r   r   r   )r   
audio_infor!   r!   r"   _proto_infog   s   zAudioFrame._proto_infoc                 C      | j S )zH
        Returns the user data associated with the audio frame.
        )r   r   r!   r!   r"   r
   o   s   zAudioFrame.userdatac                 C   s   t | jddS )z
        Returns a memory view of the audio data as 16-bit signed integers.

        Returns:
            memoryview: A memory view of the audio data.
        r   h)r   r   r   r6   r!   r!   r"   r   v   s   zAudioFrame.datac                 C   r5   )zw
        Returns the sample rate of the audio frame.

        Returns:
            int: The sample rate in Hz.
        )r   r6   r!   r!   r"   r         zAudioFrame.sample_ratec                 C   r5   )z
        Returns the number of channels in the audio frame.

        Returns:
            int: The number of audio channels (e.g., 1 for mono, 2 for stereo).
        )r   r6   r!   r!   r"   r      r8   zAudioFrame.num_channelsc                 C   r5   )z
        Returns the number of samples per channel.

        Returns:
            int: The number of samples per channel.
        )r   r6   r!   r!   r"   r      r8   zAudioFrame.samples_per_channelc                 C   s   | j | j S )z
        Returns the duration of the audio frame in seconds.

        Returns:
            float: The duration in seconds.
        )r   r   r6   r!   r!   r"   duration   s   zAudioFrame.durationc              	   C   s   ddl }ddl}| 9}||d}|| j |d || j |	| j
 W d   n1 s5w   Y  | W  d   S 1 sHw   Y  dS )z
        Convert the audio frame data to a WAV-formatted byte stream.

        Returns:
            bytes: The audio data encoded in WAV format.
        r   Nwb   )waveioBytesIOopensetnchannelsr   setsampwidthsetframerater   writeframesr   getvalue)r   r<   r=   wav_filewavr!   r!   r"   to_wav_bytes   s   

$zAudioFrame.to_wav_bytesc              	   C   s(   d| j  d| j d| j d| jdd	S )Nzrtc.AudioFrame(sample_rate=z, num_channels=z, samples_per_channel=z, duration=z.3f))r   r   r   r9   r6   r!   r!   r"   __repr__   s   
zAudioFrame.__repr___c                    s   ddl m} dd l dtddf fdd}|j|||| ||	 ||	 ||	 d|
|g|
|| fd	d
dS )Nr   )core_schemavaluer   r	   c                    sX   t | tr| S t | tr| d } t | tr(t | d | d | d | d dS td)Nr   r   r   r   r   r   r   r   r   zInvalid type for AudioFrame)r   r	   tupledict	b64decode	TypeError)rL   base64r!   r"   validate_audio_frame   s   


zEAudioFrame.__get_pydantic_core_schema__.<locals>.validate_audio_framerM   c                    s"     | jd| j| j| jdS )Nzutf-8rM   )	b64encoder   decoder   r   r   )instancerR   r!   r"   <lambda>   s
   z9AudioFrame.__get_pydantic_core_schema__.<locals>.<lambda>)json_schemapython_schemaserialization)pydantic_corerK   rS   r   json_or_python_schemachain_schemamodel_fields_schemamodel_field
str_schema
int_schema no_info_plain_validator_function$plain_serializer_function_ser_schema)clsrJ   rK   rT   r!   rR   r"   __get_pydantic_core_schema__   s,   

z'AudioFrame.__get_pydantic_core_schema__) __name__
__module____qualname____doc__r   bytesr$   r   intrO   strr   r#   staticmethodr&   r1   OwnedAudioFrameBufferr0   r2   r4   propertyr
   r   r   r   r   floatr9   rG   rI   classmethodrf   r!   r!   r!   r"   r	      sJ    
.					r	   )r   _ffi_clientr   _protor   r1   _utilsr   r   typingr   r   r	   r!   r!   r!   r"   <module>   s   