o
    i_3                     @  s   d dl mZ d dlZd dlZd dlmZ d dlmZmZm	Z	 ddl
mZmZ ddlmZ ddlmZ dd	lmZ dd
lmZmZ ddlmZ ddlmZ ddlmZ ddlmZ ddlm Z  eG dd dZ!eG dd dZ"G dd dZ#dS )    )annotationsN)	dataclass)AnyAsyncIteratorOptional   )	FfiClient	FfiHandle)audio_frame_pb2)ffi_pb2)TrackSource)	RingQueuetask_done_logger)
AudioFrame)logger)Participant)Track)FrameProcessorc                   @  s   e Zd ZU dZded< dS )AudioFrameEventzyAn event representing a received audio frame.

    Attributes:
        frame (AudioFrame): The received audio frame.
    r   frameN)__name__
__module____qualname____doc____annotations__ r   r   Z/var/www/html/livekit_bhavya/venv/lib/python3.10/site-packages/livekit/rtc/audio_stream.pyr   "   s   
 r   c                   @  s   e Zd ZU ded< ded< dS )NoiseCancellationOptionsstr	module_idzdict[str, Any]optionsN)r   r   r   r   r   r   r   r   r   -   s   
 r   c                   @  s   e Zd ZdZ						d5d6ddZedddddddd7ddZedddddddd8ddZd9dd Zd:d"d#Z	d;d$d%Z
d&d' Zd9d(d)Zd<d-d.Zd=d0d1Zd>d3d4ZdS )?AudioStreamaO  An asynchronous audio stream for receiving audio frames from a participant or track.

    The `AudioStream` class provides an asynchronous iterator over audio frames received from
    a specific track or participant. It allows you to receive audio frames in real-time with
    customizable sample rates and channel configurations.
    Nr   逻  r   trackr   loop#Optional[asyncio.AbstractEventLoop]capacityintsample_ratenum_channelsframe_size_ms
int | Nonenoise_cancellation?Optional[NoiseCancellationOptions | FrameProcessor[AudioFrame]]returnNonec           
      K  s   || _ || _|| _|| _|pt | _tjj	j
| jdd d| _t|| _d| _d| _d| _t|tr<|j| _|j| _nt|trD|| _| j|  | _| jt d}	d|v re| j|d |d d}	n|  }	t|	jj| _ |	j!| _"dS )aR  Initialize an `AudioStream` instance.

        Args:
            track (Optional[Track]): The audio track from which to receive audio. If not provided,
                you must specify `participant` and `track_source` in `kwargs`.
            loop (Optional[asyncio.AbstractEventLoop], optional): The event loop to use.
                Defaults to the current event loop.
            capacity (int, optional): The capacity of the internal frame queue. Defaults to 0 (unbounded).
            sample_rate (int, optional): The sample rate for the audio stream in Hz.
                Defaults to 48000.
            num_channels (int, optional): The number of audio channels. Defaults to 1.
            noise_cancellation (Optional[NoiseCancellationOptions | FrameProcessor[AudioFrame]], optional):
                If noise cancellation is used, pass a `NoiseCancellationOptions` or `FrameProcessor[AudioFrame]` instance
                created by the noise cancellation module.

        Example:
            ```python
            audio_stream = AudioStream(
                track=audio_track,
                sample_rate=44100,
                num_channels=2,
            )

            audio_stream = AudioStream.from_track(
                track=audio_track,
                sample_rate=44100,
                num_channels=2,
            )
            ```
        c                 S  s   |  ddkS )Nmessageaudio_stream_event)
WhichOneof)er   r   r   <lambda>m   s    z&AudioStream.__init__.<locals>.<lambda>)	filter_fnNparticipanttrack_source)r6   r7   )#_track_sample_rate_num_channels_frame_size_msasyncioget_event_loop_loopr   instancequeue	subscribe
_ffi_queuer   _queue_audio_filter_module_audio_filter_options
_processor
isinstancer   r   r    r   create_task_run_taskadd_done_callbackr   %_create_owned_stream_from_participant_create_owned_streamr	   handleid_ffi_handleinfo_info)
selfr#   r$   r&   r(   r)   r*   r,   kwargsstreamr   r   r   __init__;   s8   )



zAudioStream.__init__)r$   r&   r(   r)   r*   r,   r6   r   r7   TrackSource.ValueTypec          	      C  s   t ||||d||||d	S )a2  Create an `AudioStream` from a participant's audio track.

        Args:
            participant (Participant): The participant from whom to receive audio.
            track_source (TrackSource.ValueType): The source of the audio track (e.g., microphone, screen share).
            loop (Optional[asyncio.AbstractEventLoop], optional): The event loop to use. Defaults to the current event loop.
            capacity (int, optional): The capacity of the internal frame queue. Defaults to 0 (unbounded).
            sample_rate (int, optional): The sample rate for the audio stream in Hz. Defaults to 48000.
            num_channels (int, optional): The number of audio channels. Defaults to 1.
            noise_cancellation (Optional[NoiseCancellationOptions], optional):
                If noise cancellation is used, pass a `NoiseCancellationOptions` instance
                created by the noise cancellation module.

        Returns:
            AudioStream: An instance of `AudioStream` that can be used to receive audio frames.

        Example:
            ```python
            audio_stream = AudioStream.from_participant(
                participant=participant,
                track_source=TrackSource.MICROPHONE,
                sample_rate=24000,
                num_channels=1,
            )
            ```
        N)	r6   r7   r$   r&   r#   r(   r)   r,   r*   r!   )	clsr6   r7   r$   r&   r(   r)   r*   r,   r   r   r   from_participant   s   'zAudioStream.from_participantc             	   C  s   t |||||||dS )ap  Create an `AudioStream` from an existing audio track.

        Args:
            track (Track): The audio track from which to receive audio.
            loop (Optional[asyncio.AbstractEventLoop], optional): The event loop to use. Defaults to the current event loop.
            capacity (int, optional): The capacity of the internal frame queue. Defaults to 0 (unbounded).
            sample_rate (int, optional): The sample rate for the audio stream in Hz. Defaults to 48000.
            num_channels (int, optional): The number of audio channels. Defaults to 1.
            noise_cancellation (Optional[NoiseCancellationOptions], optional):
                If noise cancellation is used, pass a `NoiseCancellationOptions` instance
                created by the noise cancellation module.

        Returns:
            AudioStream: An instance of `AudioStream` that can be used to receive audio frames.

        Example:
            ```python
            audio_stream = AudioStream.from_track(
                track=audio_track,
                sample_rate=44100,
                num_channels=2,
            )
            ```
        )r#   r$   r&   r(   r)   r,   r*   rX   )rY   r#   r$   r&   r(   r)   r*   r,   r   r   r   
from_track   s   $zAudioStream.from_trackc                 C  s   t jj| j d S N)r   r?   r@   unsubscriberB   rS   r   r   r   __del__   s   zAudioStream.__del__r   c                 C  s   | j d usJ t }|j}| j jj|_| j|_| j	|_
| jr#| j|_tjj|_| jd ur1| j|_| jd ur=t| j|_tj|}|jjS r\   )r8   	proto_ffi
FfiRequestnew_audio_streamrP   rN   track_handler9   r(   r:   r)   r;   r*   proto_audio_frameAudioStreamTypeAUDIO_STREAM_NATIVEtyperD   audio_filter_module_idrE   jsondumpsaudio_filter_optionsr   r?   requestrU   )rS   reqrb   respr   r   r   rM      s   


z AudioStream._create_owned_streamc                 C  s   t  }|j}|jj|_| j|_| j|_	t
jj|_||_| jr#| j|_| jd ur,| j|_| jd ur8t| j|_tj|}|jjS r\   )r`   ra   audio_stream_from_participantrP   rN   participant_handler9   r(   r:   r)   rd   re   rf   rg   r7   r;   r*   rD   rh   rE   ri   rj   rk   r   r?   rl   rU   )rS   r6   r7   rm   ro   rn   r   r   r   rL      s"   



z1AudioStream._create_owned_stream_from_participantc                   s   	 | j | jI d H }|j}|drJ|jj}t|}| j	d ur?| j	j
r?z| j	|}W n ty>   tjddd Y nw t|}| j| n|drV| jd  nqtjj| j  d S )NTframe_receivedz7Frame processing failed, passing through original frame)exc_infoeos)rB   wait_for	_is_eventr1   HasFieldrq   r   r   _from_owned_inforF   enabled_process	Exceptionr   warningr   rC   putr   r?   r@   r]   )rS   eventaudio_eventowned_buffer_infor   r   r   r   rI     s.   



zAudioStream._runc                   s   | j   | jI dH  dS )zAsynchronously close the audio stream.

        This method cleans up resources associated with the audio stream and waits for
        any pending operations to complete.
        N)rP   disposerJ   r^   r   r   r   aclose*  s   
zAudioStream.acloser3   proto_ffi.FfiEventboolc                 C  s   |j j| jjkS r\   )r1   stream_handlerP   rN   )rS   r3   r   r   r   ru   3  s   zAudioStream._is_eventAsyncIterator[AudioFrameEvent]c                 C  s   | S r\   r   r^   r   r   r   	__aiter__6  s   zAudioStream.__aiter__r   c                   s0   | j  rt| j I d H }|d u rt|S r\   )rJ   doneStopAsyncIterationrC   get)rS   itemr   r   r   	__anext__9  s   
zAudioStream.__anext__)Nr   r"   r   NN)r#   r   r$   r%   r&   r'   r(   r'   r)   r'   r*   r+   r,   r-   r.   r/   )r6   r   r7   rW   r$   r%   r&   r'   r(   r'   r)   r'   r*   r+   r,   r-   r.   r!   )r#   r   r$   r%   r&   r'   r(   r'   r)   r'   r*   r+   r,   r-   r.   r!   )r.   r/   )r.   r   )r6   r   r7   rW   r.   r   )r3   r   r.   r   )r.   r   )r.   r   )r   r   r   r   rV   classmethodrZ   r[   r_   rM   rL   rI   r   ru   r   r   r   r   r   r   r!   3   sB    
L2
-



	
r!   )$
__future__r   r<   ri   dataclassesr   typingr   r   r   _ffi_clientr   r	   _protor
   rd   r   r`   _proto.track_pb2r   _utilsr   r   audio_framer   logr   r6   r   r#   r   frame_processorr   r   r   r!   r   r   r   r   <module>   s(   
