o
    i                  
   @   s  d Z ddlZddlZddlZddlmZ ddlmZmZm	Z	m
Z
mZ ddlZddlmZ ddlmZ ddlmZmZmZmZmZmZmZmZmZmZmZmZ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+ zddl,Z,ddl-m.Z. ddl/m0Z0m1Z1 ddl2m3Z3m4Z4m5Z5 W n  e6y Z7 ze8de7  e8d e9de7 dZ7[7ww dZ:dZ;dZ<G dd deZ=G dd de0Z>G dd de.Z?G dd dZ@G dd de$ZAG d d! d!e&ZBG d"d# d#e(ZCdS )$a	  Small WebRTC transport implementation for Pipecat.

This module provides a WebRTC transport implementation using aiortc for
real-time audio and video communication. It supports bidirectional media
streaming, application messaging, and client connection management.
    N)deque)Any	AwaitableCallableListOptional)logger)	BaseModel)CancelFrameClientConnectedFrameEndFrameFrameInputAudioRawFrameInputTransportMessageFrameOutputAudioRawFrameOutputImageRawFrameOutputTransportMessageFrame!OutputTransportMessageUrgentFrameSpriteFrame
StartFrameUserImageRawFrameUserImageRequestFrame)FrameDirection)BaseInputTransport)BaseOutputTransport)BaseTransportTransportParams)SmallWebRTCConnection)VideoStreamTrack)AudioStreamTrackMediaStreamError)
AudioFrameAudioResampler
VideoFramezException: zNIn order to use the SmallWebRTC, you need to `pip install pipecat-ai[webrtc]`.zMissing module: camerascreenVideo
microphonec                   @   sV   e Zd ZU dZeeeged f ed< ee	ged f ed< ee	ged f ed< dS )SmallWebRTCCallbacksa  Callback handlers for SmallWebRTC events.

    Parameters:
        on_app_message: Called when an application message is received.
        on_client_connected: Called when a client establishes connection.
        on_client_disconnected: Called when a client disconnects.
    Non_app_messageon_client_connectedon_client_disconnected)
__name__
__module____qualname____doc__r   r   strr   __annotations__r    r1   r1   \/home/ubuntu/.local/lib/python3.10/site-packages/pipecat/transports/smallwebrtc/transport.pyr'   =   s
   
 r'   c                       s6   e Zd ZdZ fddZdefddZdd Z  ZS )	RawAudioTrackzCustom audio stream track for WebRTC output.

    Handles audio frame generation and timing for WebRTC transmission,
    supporting queued audio data with proper synchronization.
    c                    sF   t    || _|d d | _| jd | _d| _t | _t | _	dS )zmInitialize the raw audio track.

        Args:
            sample_rate: The audio sample rate in Hz.
        
   i     r   N)
super__init___sample_rate_samples_per_10ms_bytes_per_10ms
_timestamptime_startr   _chunk_queue)selfsample_rate	__class__r1   r2   r7   R   s   

zRawAudioTrack.__init__audio_bytesc                 C   s~   t || j dkrtdt  }tdt || jD ] }|||| j  }|| j t |kr2|nd}| j||f q|S )a5  Add audio bytes to the buffer for transmission.

        Args:
            audio_bytes: Raw audio data to queue for transmission.

        Returns:
            A Future that completes when the data is processed.

        Raises:
            ValueError: If audio bytes are not a multiple of 10ms size.
        r   z,Audio bytes must be a multiple of 10ms size.N)	lenr:   
ValueErrorasyncioget_running_loopcreate_futureranger>   append)r?   rC   futureichunkfutr1   r1   r2   add_audio_bytesa   s   zRawAudioTrack.add_audio_bytesc                    s   | j dkr| j| j | j  t  }|dkrt|I dH  | jr5| j \}}|r4| s4|	d nt
| j}tj|tjd}tj|dddf dd}| j|_| j |_td| j|_|  j | j7  _ |S )zReturn the next audio frame for WebRTC transmission.

        Returns:
            An AudioFrame containing the next audio data or silence.
        r   NTdtypemono)layout   )r;   r=   r8   r<   rF   sleepr>   popleftdone
set_resultbytesr:   np
frombufferint16r!   from_ndarrayr@   pts	fractionsFraction	time_baser9   )r?   waitrM   rK   samplesframer1   r1   r2   recvz   s$   


zRawAudioTrack.recv)	r+   r,   r-   r.   r7   rY   rO   re   __classcell__r1   r1   rA   r2   r3   K   s
    r3   c                       s0   e Zd ZdZ fddZdd Zdd Z  ZS )RawVideoTrackzzCustom video stream track for WebRTC output.

    Handles video frame queuing and conversion for WebRTC transmission.
    c                    s$   t    || _|| _t | _dS )zInitialize the raw video track.

        Args:
            width: Video frame width in pixels.
            height: Video frame height in pixels.
        N)r6   r7   _width_heightrF   Queue_video_buffer)r?   widthheightrA   r1   r2   r7      s   
zRawVideoTrack.__init__c                 C   s   | j | dS )zAdd a video frame to the transmission buffer.

        Args:
            frame: The video frame to queue for transmission.
        N)rk   
put_nowaitr?   rd   r1   r1   r2   add_video_frame   s   zRawVideoTrack.add_video_framec                    s\   | j  I dH }tj|jtjd| j| jdf}t	j
|dd}|  I dH \|_|_|S )zReturn the next video frame for WebRTC transmission.

        Returns:
            A VideoFrame ready for WebRTC transmission.
        NrP      rgb24format)rk   getrZ   r[   imageuint8reshaperi   rh   r#   r]   next_timestampr^   ra   )r?   	raw_frame
frame_datard   r1   r1   r2   re      s   zRawVideoTrack.recv)r+   r,   r-   r.   r7   rp   re   rf   r1   r1   rA   r2   rg      s
    rg   c                   @   s  e Zd ZdZejejejejdZde	de
fddZdejded	ejfd
dZdefddZdd Zded	efddZded	efddZdefddZdd Zdd ZdeeB fddZdd  Zd!d" Zd#d$ Z d%e!d&efd'd(Z"d)d* Z#e$d	efd+d,Z%e$d	efd-d.Z&d/S )0SmallWebRTCClientzWebRTC client implementation for handling connections and media streams.

    Manages WebRTC peer connections, audio/video streaming, and application
    messaging through the SmallWebRTCConnection interface.
    )yuv420pyuvj420pnv12graywebrtc_connection	callbacksc                    s   | _ d _| _d _d _d _d _d _d _d _	d _
d _d _d _ j ddtf fdd} j ddtf fd	d
} j ddtf fdd} j ddtdtf fdd}dS )zInitialize the WebRTC client.

        Args:
            webrtc_connection: The underlying WebRTC connection handler.
            callbacks: Event callbacks for connection and message handling.
        FNr   	connected
connectionc                       t d   I d H  d S )NzPeer connection established.)r   debug_handle_client_connectedr   r?   r1   r2   on_connected      
z0SmallWebRTCClient.__init__.<locals>.on_connecteddisconnectedc                    r   )NzPeer connection lost.)r   r   _handle_peer_disconnectedr   r   r1   r2   on_disconnected   r   z3SmallWebRTCClient.__init__.<locals>.on_disconnectedclosedc                    r   )NzClient connection closed.)r   r   _handle_client_closedr   r   r1   r2   	on_closed   r   z-SmallWebRTCClient.__init__.<locals>.on_closedzapp-messagemessagec                    s     || jI d H  d S )N)_handle_app_messagepc_id)r   r   r   r1   r2   r(         z2SmallWebRTCClient.__init__.<locals>.on_app_message)_webrtc_connection_closing
_callbacks_audio_output_track_video_output_track_audio_input_track_video_input_track_screen_video_track_params_audio_in_channels_in_sample_rate_out_sample_rate_leave_counter_audio_in_resamplerevent_handlerr   r   )r?   r   r   r   r   r   r(   r1   r   r2   r7      s,   



zSmallWebRTCClient.__init__frame_arrayformat_namereturnc                 C   s<   | dr|S tj|}|du rtd| t||S )aX  Convert a video frame to RGB format based on the input format.

        Args:
            frame_array: The input frame as a NumPy array.
            format_name: The format of the input frame.

        Returns:
            The converted RGB frame as a NumPy array.

        Raises:
            ValueError: If the format is unsupported.
        rgbNzUnsupported format: )
startswithr|   FORMAT_CONVERSIONSru   rE   cv2cvtColor)r?   r   r   conversion_coder1   r1   r2   _convert_frame  s   
z SmallWebRTCClient._convert_framevideo_sourcec           	      C  s,  	 |t kr	| jn| j}|du rtdI dH  qztj| ddI dH }W n+ tjyC   | j	 r?|r?|
 r?td d}Y n tyR   td d}Y nw |du s\t|tsetdI dH  q|jj}|j|d}| ||}~| }~t| jj||j|jfd	d
}||_|j|_~~|V  q)am  Read video frames from the WebRTC connection.

        Reads a video frame from the given MediaStreamTrack, converts it to RGB,
        and creates an InputImageRawFrame.

        Args:
            video_source: Video source to capture ("camera" or "screenVideo").

        Yields:
            UserImageRawFrame objects containing video data from the peer.
        TN{Gz?       @timeoutz;Timeout: No video frame received within the specified time.zBReceived an unexpected media stream error while reading the video.rs   RGB)user_idrv   sizert   )CAM_VIDEO_SOURCEr   r   rF   rU   wait_forre   TimeoutErrorr   is_connected
is_enabledr   warningr    
isinstancer#   rt   name
to_ndarrayr   tobytesr   r   rl   rm   transport_sourcer^   )	r?   r   video_trackrd   r   r   	frame_rgbimage_bytesimage_framer1   r1   r2   read_video_frame  sZ   


z"SmallWebRTCClient.read_video_framec                 C  s&  	 | j du rtdI dH  qztj| j  ddI dH }W n- tjy=   | j r9| j r9| j  r9t	
d d}Y n tyL   t	
d d}Y nw |du sVt|ts_tdI dH  q|j| jkrk| j|n|g}|D ] }| tj}| }~t|| j| jd}|j|_~|V  qp~q)	zRead audio frames from the WebRTC connection.

        Reads 20ms of audio from the given MediaStreamTrack and creates an InputAudioRawFrame.

        Yields:
            InputAudioRawFrame objects containing audio data from the peer.
        TNr   r   r   z;Timeout: No audio frame received within the specified time.zBReceived an unexpected media stream error while reading the audio.)audior@   num_channels)r   rF   rU   r   re   r   r   r   r   r   r   r    r   r!   r@   r   r   resampler   astyperZ   r\   r   r   r   r^   )r?   rd   frames_to_processprocessed_frame	pcm_array	pcm_bytesaudio_framer1   r1   r2   read_audio_frameZ  sR   


z"SmallWebRTCClient.read_audio_framerd   c                    s,   |   r| jr| j|jI dH  dS dS )zWrite an audio frame to the WebRTC connection.

        Args:
            frame: The audio frame to transmit.

        Returns:
            True if the audio frame was written successfully, False otherwise.
        NTF)	_can_sendr   rO   r   ro   r1   r1   r2   write_audio_frame  s
   	z#SmallWebRTCClient.write_audio_framec                    s$   |   r| jr| j| dS dS )zWrite a video frame to the WebRTC connection.

        Args:
            frame: The video frame to transmit.

        Returns:
            True if the video frame was written successfully, False otherwise.
        TF)r   r   rp   ro   r1   r1   r2   write_video_frame  s
   	z#SmallWebRTCClient.write_video_framer   c                    sN   |j | _|jp
|j| _|jp|j| _|| _|  jd7  _tdd| j| _	dS )zSet up the client with transport parameters.

        Args:
            _params: Transport configuration parameters.
            frame: The initialization frame containing setup data.
        rT   s16rR   N)
audio_in_channelsr   audio_in_sample_rater   audio_out_sample_rater   r   r   r"   r   )r?   r   rd   r1   r1   r2   setup  s   zSmallWebRTCClient.setupc                    s.   | j  rdS td | j  I dH  dS )z Establish the WebRTC connection.NzConnecting to Small WebRTC)r   r   r   infoconnectr   r1   r1   r2   r     s
   

zSmallWebRTCClient.connectc                    sd   |  j d8  _ | j dkrdS | jr.| js0td d| _| j I dH  |  I dH  dS dS dS )z Disconnect from the WebRTC peer.rT   r   NzDisconnecting to Small WebRTCT)	r   r   
is_closingr   r   r   r   
disconnectr   r   r1   r1   r2   r     s   

zSmallWebRTCClient.disconnectc                    s    |   r| j|j dS dS )zSend an application message through the WebRTC connection.

        Args:
            frame: The message frame to send.
        N)r   r   send_app_messager   ro   r1   r1   r2   send_message  s   zSmallWebRTCClient.send_messagec                    s   | j sdS | j | _| j | _| j | _| j jr*t	| j
d| _| j| j | j jr@t| j j| j jd| _| j| j | j| jI dH  dS )z'Handle client connection establishment.N)r@   )rl   rm   )r   r   audio_input_trackr   video_input_trackr   screen_video_input_trackr   audio_out_enabledr3   r   r   replace_audio_trackvideo_out_enabledrg   video_out_widthvideo_out_heightr   replace_video_trackr   r)   r   r1   r1   r2   r     s   z*SmallWebRTCClient._handle_client_connectedc                    s$   d| _ d| _d| _d| _d| _dS )z"Handle peer disconnection cleanup.N)r   r   r   r   r   r   r1   r1   r2   r     s   
z+SmallWebRTCClient._handle_peer_disconnectedc                    sB   d| _ d| _d| _d| _d| _| js| j| jI dH  dS dS )z!Handle client connection closure.N)	r   r   r   r   r   r   r   r*   r   r   r1   r1   r2   r     s   z'SmallWebRTCClient._handle_client_closedr   senderc                    s   | j ||I dH  dS )%Handle incoming application messages.N)r   r(   r?   r   r   r1   r1   r2   r     r   z%SmallWebRTCClient._handle_app_messagec                 C   s   | j o| j S )z2Check if the connection is ready for sending data.)r   r   r   r1   r1   r2   r     s   zSmallWebRTCClient._can_sendc                 C   s
   | j  S )ztCheck if the WebRTC connection is established.

        Returns:
            True if connected to the peer.
        )r   r   r   r1   r1   r2   r     s   
zSmallWebRTCClient.is_connectedc                 C   s   | j S )zCheck if the connection is in the process of closing.

        Returns:
            True if the connection is closing.
        )r   r   r1   r1   r2   r     s   zSmallWebRTCClient.is_closingN)'r+   r,   r-   r.   r   COLOR_YUV2RGB_I420COLOR_YUV2RGB_NV12COLOR_GRAY2RGBr   r   r'   r7   rZ   ndarrayr/   r   r   r   r   boolr   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   propertyr   r   r1   r1   r1   r2   r|      s8    -@9	
r|   c                       s   e Zd ZdZdedef fddZdedef fdd	Z	de
f fd
dZdd Zdef fddZdef fddZdd ZdefddZdefddZdefddZefdefddZ  ZS )SmallWebRTCInputTransportzInput transport implementation for SmallWebRTC.

    Handles incoming audio and video streams from WebRTC peers,
    including user image requests and application message handling.
    clientparamsc                    sB   t  j|fi | || _|| _d| _d| _d| _g | _d| _dS )zInitialize the WebRTC input transport.

        Args:
            client: The WebRTC client instance.
            params: Transport configuration parameters.
            **kwargs: Additional arguments passed to parent class.
        NF)	r6   r7   _clientr   _receive_audio_task_receive_video_task_receive_screen_video_task_image_requests_initializedr?   r   r   kwargsrA   r1   r2   r7   )  s   
z"SmallWebRTCInputTransport.__init__rd   	directionc                    s8   t  ||I dH  t|tr| |I dH  dS dS )zProcess incoming frames including user image requests.

        Args:
            frame: The frame to process.
            direction: The direction of frame flow in the pipeline.
        N)r6   process_framer   r   request_participant_image)r?   rd   r   rA   r1   r2   r   A  s
   
z'SmallWebRTCInputTransport.process_framec                    s   t  |I dH  | jrdS d| _| j| j|I dH  | j I dH  | |I dH  | js<| jj	r<| 
|  | _| jsN| jjrP| 
| t| _dS dS dS )zStart the input transport and establish WebRTC connection.

        Args:
            frame: The start frame containing initialization parameters.
        NT)r6   startr   r   r   r   r   set_transport_readyr   audio_in_enabledcreate_task_receive_audior   video_in_enabled_receive_videor   ro   rA   r1   r2   r   M  s   zSmallWebRTCInputTransport.startc                    sF   | j r| | j I dH  d| _ | jr!| | jI dH  d| _dS dS )zStop all background tasks.N)r   cancel_taskr   r   r1   r1   r2   _stop_tasksb  s   
z%SmallWebRTCInputTransport._stop_tasksc                    6   t  |I dH  |  I dH  | j I dH  dS )zStop the input transport and disconnect from WebRTC.

        Args:
            frame: The end frame signaling transport shutdown.
        N)r6   stopr  r   r   ro   rA   r1   r2   r	  k     zSmallWebRTCInputTransport.stopc                    r  )zCancel the input transport and disconnect immediately.

        Args:
            frame: The cancel frame signaling immediate cancellation.
        N)r6   cancelr  r   r   ro   rA   r1   r2   r  u  r
  z SmallWebRTCInputTransport.cancelc                    s   z| j  }|2 z3 dH W }|r| |I dH  q	6 W dS  ty@ } zt|  d|jj d| d W Y d}~dS d}~ww )z7Background task for receiving audio frames from WebRTC.N exception receiving data:  ())r   r   push_audio_frame	Exceptionr   errorrB   r+   )r?   audio_iteratorr   er1   r1   r2   r    s   
.z(SmallWebRTCInputTransport._receive_audior   c           	         s   zZ| j |}|2 zM3 dH W }|rW| |I dH  | jdd D ]5}|r(|jnd}|r/|jnd}|j|krVt|j|j	|j
|j|||d}||_| |I dH  | j| q!q
6 W dS  ty~ } zt|  d|jj d| d W Y d}~dS d}~ww )zBackground task for receiving video frames from WebRTC.

        Args:
            video_source: Video source to capture ("camera" or "screenVideo").
        N)r   rv   r   rt   textappend_to_contextrequestr  r  r  )r   r   push_video_framer   r  r  r   r   r   rv   r   rt   r   remover  r   r  rB   r+   )	r?   r   video_iteratorvideo_framerequest_framerequest_textadd_to_contextr   r  r1   r1   r2   r    s8   
	.z(SmallWebRTCInputTransport._receive_videor   c                    s*   t d|  | jt|dI dH  dS )zPush an application message into the pipeline.

        Args:
            message: The application message to process.
        z7Received app message inside SmallWebRTCInputTransport  )r   N)r   r   broadcast_framer   )r?   r   r1   r1   r2   push_app_message  s   z*SmallWebRTCInputTransport.push_app_messagec                    s   t d|j  | j| |jdu rt|_|jtkr/| js/| jj	r/| 
| t| _dS |jtkrF| jsH| jj	rJ| 
| t| _dS dS dS dS )a.  Request an image frame from the participant's video stream.

        When a UserImageRequestFrame is received, this method will store the request
        and the next video frame received will be converted to a UserImageRawFrame.

        Args:
            frame: The user image request frame.
        z#Requesting image from participant: N)r   r   r   r   rJ   r   r   r   r   r  r  r  SCREEN_VIDEO_SOURCEr   ro   r1   r1   r2   r     s(   	



z3SmallWebRTCInputTransport.request_participant_imagesourcec                    s   |t kr| js| jjr| |  | _dS |tkr,| js,| jjr,| | 	t| _dS |t
krB| jsD| jjrF| | 	t
| _dS dS dS dS )zCapture media from a specific participant.

        Args:
            source: Media source to capture from. ("camera", "microphone", or "screenVideo")
        N)MIC_AUDIO_SOURCEr   r   r  r  r  r   r   r  r  r   r   )r?   r!  r1   r1   r2   capture_participant_media  s,   
z3SmallWebRTCInputTransport.capture_participant_media)r+   r,   r-   r.   r|   r   r7   r   r   r   r   r   r  r   r	  r
   r  r  r/   r  r   r  r   r   r   r#  rf   r1   r1   rA   r2   r   "  s(    	

&
%r   c                       s   e Zd ZdZdedef fddZdef fddZde	f fd	d
Z
def fddZdeeB fddZdedefddZdedefddZ  ZS )SmallWebRTCOutputTransportzOutput transport implementation for SmallWebRTC.

    Handles outgoing audio and video streams to WebRTC peers,
    including transport message sending.
    r   r   c                    s*   t  j|fi | || _|| _d| _dS )zInitialize the WebRTC output transport.

        Args:
            client: The WebRTC client instance.
            params: Transport configuration parameters.
            **kwargs: Additional arguments passed to parent class.
        FN)r6   r7   r   r   r   r   rA   r1   r2   r7     s   
z#SmallWebRTCOutputTransport.__init__rd   c                    s^   t  |I dH  | jrdS d| _| j| j|I dH  | j I dH  | |I dH  dS )zStart the output transport and establish WebRTC connection.

        Args:
            frame: The start frame containing initialization parameters.
        NT)r6   r   r   r   r   r   r   r   ro   rA   r1   r2   r     s   z SmallWebRTCOutputTransport.startc                    (   t  |I dH  | j I dH  dS )zStop the output transport and disconnect from WebRTC.

        Args:
            frame: The end frame signaling transport shutdown.
        N)r6   r	  r   r   ro   rA   r1   r2   r	  ,     zSmallWebRTCOutputTransport.stopc                    r%  )zCancel the output transport and disconnect immediately.

        Args:
            frame: The cancel frame signaling immediate cancellation.
        N)r6   r  r   r   ro   rA   r1   r2   r  5  r&  z!SmallWebRTCOutputTransport.cancelc                    s   | j |I dH  dS )zSend a transport message through the WebRTC connection.

        Args:
            frame: The transport message frame to send.
        N)r   r   ro   r1   r1   r2   r   >  s   z'SmallWebRTCOutputTransport.send_messager   c                       | j |I dH S )zWrite an audio frame to the WebRTC connection.

        Args:
            frame: The output audio frame to transmit.

        Returns:
            True if the audio frame was written successfully, False otherwise.
        N)r   r   ro   r1   r1   r2   r   H     	z,SmallWebRTCOutputTransport.write_audio_framec                    r'  )zWrite a video frame to the WebRTC connection.

        Args:
            frame: The output video frame to transmit.

        Returns:
            True if the video frame was written successfully, False otherwise.
        N)r   r   ro   r1   r1   r2   r   S  r(  z,SmallWebRTCOutputTransport.write_video_frame)r+   r,   r-   r.   r|   r   r7   r   r   r   r	  r
   r  r   r   r   r   r   r   r   r   rf   r1   r1   rA   r2   r$     s    		

r$  c                
       s   e Zd ZdZ		d!dededee dee f fddZd	e	fd
dZ
d	efddZdeeB fddZdefddZdedefddZdd Zdd ZefdefddZefdefdd Z  ZS )"SmallWebRTCTransporta  WebRTC transport implementation for real-time communication.

    Provides bidirectional audio and video streaming over WebRTC connections
    with support for application messaging and connection event handling.

    Event handlers available:

    - on_client_connected(transport, client): Client connected to WebRTC session
    - on_client_disconnected(transport, client): Client disconnected from WebRTC session
    - on_client_message(transport, message, client): Received a data channel message

    Example::

        @transport.event_handler("on_client_connected")
        async def on_client_connected(transport, client):
            ...
    Nr   r   
input_nameoutput_namec                    sh   t  j||d || _t| j| j| jd| _t|| j| _	d| _
d| _| d | d | d dS )a9  Initialize the WebRTC transport.

        Args:
            webrtc_connection: The underlying WebRTC connection handler.
            params: Transport configuration parameters.
            input_name: Optional name for the input processor.
            output_name: Optional name for the output processor.
        )r*  r+  )r(   r)   r*   Nr(   r)   r*   )r6   r7   r   r'   _on_app_message_on_client_connected_on_client_disconnectedr   r|   r   _input_output_register_event_handler)r?   r   r   r*  r+  rA   r1   r2   r7   r  s   

zSmallWebRTCTransport.__init__r   c                 C   "   | j st| j| j| jd| _ | j S )zGet the input transport processor.

        Returns:
            The input transport for handling incoming media streams.
        r   )r/  r   r   r   _input_namer   r1   r1   r2   input  
   zSmallWebRTCTransport.inputc                 C   r2  )zGet the output transport processor.

        Returns:
            The output transport for handling outgoing media streams.
        r3  )r0  r$  r   r   r4  r   r1   r1   r2   output  r6  zSmallWebRTCTransport.outputrd   c                    &   | j r| j |tjI dH  dS dS )znSend an image frame through the transport.

        Args:
            frame: The image frame to send.
        Nr0  queue_framer   
DOWNSTREAMro   r1   r1   r2   
send_image     zSmallWebRTCTransport.send_imagec                    r8  )znSend an audio frame through the transport.

        Args:
            frame: The audio frame to send.
        Nr9  ro   r1   r1   r2   
send_audio  r=  zSmallWebRTCTransport.send_audior   r   c                    s2   | j r| j |I dH  | d||I dH  dS )r   Nr(   )r/  r  _call_event_handlerr   r1   r1   r2   r,    s   z$SmallWebRTCTransport._on_app_messagec                    s6   |  d|I dH  | jr| jt I dH  dS dS )z Handle client connection events.r)   N)r?  r/  
push_framer   r?   r   r1   r1   r2   r-    s
   z)SmallWebRTCTransport._on_client_connectedc                    s   |  d|I dH  dS )z#Handle client disconnection events.r*   N)r?  rA  r1   r1   r2   r.    s   z,SmallWebRTCTransport._on_client_disconnectedr   c                    $   | j r| j j|dI dH  dS dS )zCapture video from a specific participant.

        Args:
            video_source: Video source to capture from ("camera" or "screenVideo").
        r!  Nr/  r#  )r?   r   r1   r1   r2   capture_participant_video     	z.SmallWebRTCTransport.capture_participant_videoaudio_sourcec                    rB  )zCapture audio from a specific participant.

        Args:
            audio_source: Audio source to capture from. (currently, "microphone" is the only supported option)
        rC  NrD  )r?   rG  r1   r1   r2   capture_participant_audio  rF  z.SmallWebRTCTransport.capture_participant_audio)NN)r+   r,   r-   r.   r   r   r   r/   r7   r   r5  r$  r7  r   r   r<  r   r>  r   r,  r-  r.  r   rE  r"  rH  rf   r1   r1   rA   r2   r)  _  s8    #		
r)  )Dr.   rF   r_   r<   collectionsr   typingr   r   r   r   r   numpyrZ   logurur   pydanticr	   pipecat.frames.framesr
   r   r   r   r   r   r   r   r   r   r   r   r   r   "pipecat.processors.frame_processorr   pipecat.transports.base_inputr   pipecat.transports.base_outputr   !pipecat.transports.base_transportr   r   )pipecat.transports.smallwebrtc.connectionr   r   aiortcr   aiortc.mediastreamsr   r    avr!   r"   r#   ModuleNotFoundErrorr  r  r  r   r   r"  r'   r3   rg   r|   r   r$  r)  r1   r1   r1   r2   <module>   sN   @
N/  \ __