
    cjhi                       U d Z ddlmZ ddlZddlZddlZddlZddlZddlZddl	Z	ddl
Z
ddlZ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 ddlmZ dd	lmZ erdd
lm Z   edd      Z! edd      Z" ejF                  e$      Z%dZ&de'd<   ejP                  dk7  rdZ)ndZ) G d d      Z* G d de*      Z+ G d de*      Z, G d de,      Z- G d de,      Z. G d de*ee!         Z/ G d d ej`                        Z1y)!ae  
The MIT License (MIT)

Copyright (c) 2015-2021 Rapptz
Copyright (c) 2021-present Pycord Development

Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
    )annotationsN)IOTYPE_CHECKINGAnyCallableGenericTypeVar   )ClientException)	OggStream)Encoder)MISSING)VoiceClientATAudioSource)boundFTFFmpegOpusAudio)r   PCMAudioFFmpegAudioFFmpegPCMAudior   PCMVolumeTransformerintCREATE_NO_WINDOWwin32i   c                  0    e Zd ZdZddZddZd	dZd	dZy)
r   a  Represents an audio stream.

    The audio stream can be Opus encoded or not, however if the audio stream
    is not Opus encoded then the audio format must be 16-bit 48KHz stereo PCM.

    .. warning::

        The audio source reads are done in a separate thread.
    c                    t         )aW  Reads 20ms worth of audio.

        Subclasses must implement this.

        If the audio is complete, then returning an empty
        :term:`py:bytes-like object` to signal this is the way to do so.

        If :meth:`~AudioSource.is_opus` method returns ``True``, then it must return
        20ms worth of Opus encoded audio. Otherwise, it must be 20ms
        worth of 16-bit 48KHz stereo PCM, which is about 3,840 bytes
        per frame (20ms worth of audio).

        Returns
        -------
        :class:`bytes`
            A bytes like object that represents the PCM or Opus data.
        )NotImplementedErrorselfs    A/var/www/html/venv/lib/python3.12/site-packages/discord/player.pyreadzAudioSource.readT   s
    $ "!    c                     y)z6Checks if the audio source is already encoded in Opus.F r   s    r!   is_opuszAudioSource.is_opush   s    r#   c                     y)zCalled when clean-up is needed to be done.

        Useful for clearing buffer data or processes after
        it is done playing audio.
        Nr%   r   s    r!   cleanupzAudioSource.cleanupl   s    r#   c                $    | j                          y N)r(   r   s    r!   __del__zAudioSource.__del__s   s    r#   Nreturnbytesr-   boolr-   None)__name__
__module____qualname____doc__r"   r&   r(   r+   r%   r#   r!   r   r   I   s    "(r#   c                       e Zd ZdZddZddZy)r   zRepresents raw 16-bit 48KHz stereo PCM audio source.

    Attributes
    ----------
    stream: :term:`py:file object`
        A file-like object that reads byte data representing raw PCM.
    c                    || _         y r*   )stream)r    r9   s     r!   __init__zPCMAudio.__init__   s	    )/r#   c                    | j                   j                  t        j                        }t	        |      t        j                  k7  ry|S Nr#   )r9   r"   OpusEncoder
FRAME_SIZElenr    rets     r!   r"   zPCMAudio.read   s6    kk{556s8{---
r#   N)r9   io.BufferedIOBaser-   r2   r,   )r3   r4   r5   r6   r:   r"   r%   r#   r!   r   r   w   s    0r#   r   c                  L    e Zd ZdZdd	 	 	 	 	 	 	 d
dZddZddZddZddZy	)r   zRepresents an FFmpeg (or AVConv) based AudioSource.

    User created AudioSources using FFmpeg differently from how :class:`FFmpegPCMAudio` and
    :class:`FFmpegOpusAudio` work should subclass this.

    .. versionadded:: 1.3
    ffmpeg)
executablec               4   |j                  d      t        j                  k(  }|rt        |t              rt        d      |g|}dt        j                  i}|j                  |        | j                  |fi || _        | j                  j                  | _
        d | _        d | _        |rndt        |       d}| j                  j                  | _        t        j                   | j"                  |fd|      | _        | j                  j%                          y y )NstdinzNparameter conflict: 'source' parameter cannot be a string when piping to stdinstdoutzpopen-stdin-writer:z#xT)targetargsdaemonname)get
subprocessPIPE
isinstancestr	TypeErrorupdate_spawn_process_processrH   _stdout_stdin_pipe_threadidrG   	threadingThread_pipe_writerstart)r    sourcerE   rJ   subprocess_kwargspipingkwargsns           r!   r:   zFFmpegAudio.__init__   s    #&&w/:??Bj- 
 "T"JOO,'(*=$*=*=d*Mf*M"&--"6"6(,59%bhr]3A----DK ) 0 0((yA!D ##% r#   c                B   	 t        j                  |fdt        i|}|S # t        $ r9 t	        |t
              r|j                  d      d   n|d   }t        | d      d t         j                  $ r+}t        d|j                  j                   d|       |d }~ww xY w)Ncreationflags r   z was not found.zPopen failed: z: )rN   Popenr   FileNotFoundErrorrP   rQ   	partitionr   SubprocessError	__class__r3   )r    rJ   r_   processrE   excs         r!   rT   zFFmpegAudio._spawn_process   s    	 &&$48IG N ! 	L3=dC3H,Q/dSTgJ!ZL"@AtK)) 	! !7!7 83%@	s     AB3&BBc                   | j                   }|t        u ry t        j                  d|j                         	 |j                          |j                         \t        j                  d|j                         |j                          t        j                  d|j                  |j                         y t        j                  d|j                  |j                         y # t        $ r# t        j                  d|j                         Y w xY w)Nz)Preparing to terminate ffmpeg process %s.z3Ignoring error attempting to kill ffmpeg process %sz=ffmpeg process %s has not terminated. Waiting to terminate...zBffmpeg process %s should have terminated with a return code of %s.zAffmpeg process %s successfully terminated with return code of %s.)rU   r   _loginfopidkill	Exception	exceptionpollcommunicate
returncode)r    procs     r!   _kill_processzFFmpegAudio._kill_process   s    }}7?		=txxH	IIK 99;IIO IIT IIS#  	NNEtxx	s   C )D
Dc                N   | j                   rX|j                  d      }|s| j                  j                          y 	 | j                  j	                  |       | j                   rWy y # t
        $ r5 t        j                  d| d       | j                   j                          Y y w xY w)Ni    z2Write error for %s, this is probably not a problemTexc_info)	rU   r"   rW   closewriterr   rn   debug	terminate)r    r^   datas      r!   r\   zFFmpegAudio._pipe_writer   s    mm;;t$D!!#
!!$' mm  

H!   '')s   A& &;B$#B$c                V    | j                          t        x| _        x| _        | _        y r*   )rx   r   rU   rV   rW   r   s    r!   r(   zFFmpegAudio.cleanup   s#    5<<<t{r#   N)r^   str | io.BufferedIOBaserE   rQ   rJ   r   r_   r   )rJ   r   r_   r   r-   zsubprocess.Popenr1   )r^   rB   r-   r2   )	r3   r4   r5   r6   r:   rT   rx   r\   r(   r%   r#   r!   r   r      sM     #	&'& 	&
 & !&@@&=r#   r   c                  \     e Zd ZdZdddddd	 	 	 	 	 	 	 	 	 	 	 	 	 d	 fdZd
dZddZ xZS )r   a  An audio source from FFmpeg (or AVConv).

    This launches a sub-process to a specific input file given.

    .. warning::

        You must have the ffmpeg or avconv executable in your path environment
        variable in order for this to work.

    Parameters
    ----------
    source: Union[:class:`str`, :class:`io.BufferedIOBase`]
        The input that ffmpeg will take and convert to PCM bytes.
        If ``pipe`` is ``True`` then this is a file-like object that is
        passed to the stdin of ffmpeg.
    executable: :class:`str`
        The executable name (and path) to use. Defaults to ``ffmpeg``.
    pipe: :class:`bool`
        If ``True``, denotes that ``source`` parameter will be passed
        to the stdin of ffmpeg. Defaults to ``False``.
    stderr: Optional[:term:`py:file object`]
        A file-like object to pass to the Popen constructor.
        Could also be an instance of ``subprocess.PIPE``.
    before_options: Optional[:class:`str`]
        Extra command line arguments to pass to ffmpeg before the ``-i`` flag.
    options: Optional[:class:`str`]
        Extra command line arguments to pass to ffmpeg after the ``-i`` flag.

    Raises
    ------
    ClientException
        The subprocess failed to be created.
    rD   FN)rE   pipestderrbefore_optionsoptionsc                  g }|rt         j                  nt         j                  |d}t        |t              r$|j                  t        j                  |             |j                  d       |j                  |rdn|       |j                  d       t        |t              r$|j                  t        j                  |             |j                  d       t        	| (  |f||d| y )NrG   r   -i-)-fs16le-ar48000-ac2	-loglevelwarningpipe:1rE   rJ   )rN   rO   DEVNULLrP   rQ   extendshlexsplitappendsuperr:   )
r    r^   rE   r   r   r   r   rJ   r_   rj   s
            r!   r:   zFFmpegPCMAudio.__init__  s     (,Z__*2D2D

 nc*KKN34D4CV,WXgs#KKG,-HWJTWEVWr#   c                    | j                   j                  t        j                        }t	        |      t        j                  k7  ry|S r<   )rV   r"   r=   r>   r?   r@   s     r!   r"   zFFmpegPCMAudio.read;  s6    ll 6 67s8{---
r#   c                     yNFr%   r   s    r!   r&   zFFmpegPCMAudio.is_opusA  s    r#   )r^   r   rE   rQ   r   r0   r   zIO[str] | Noner   
str | Noner   r   r-   r2   r,   r/   )r3   r4   r5   r6   r:   r"   r&   __classcell__rj   s   @r!   r   r      su     L #!%%)"X'X 	X
 X X #X X 
X<r#   r   c                       e Zd ZdZdddddddd	 	 	 	 	 	 	 	 	 d fdZedd	 	 	 	 	 	 	 	 	 dd	       Zeddd
	 	 	 	 	 	 	 dd       Ze	 d	 	 	 dd       Z	e	 d	 	 	 dd       Z
ddZddZ xZS )r   a
  An audio source from FFmpeg (or AVConv).

    This launches a sub-process to a specific input file given.  However, rather than
    producing PCM packets like :class:`FFmpegPCMAudio` does that need to be encoded to
    Opus, this class produces Opus packets, skipping the encoding step done by the library.

    Alternatively, instead of instantiating this class directly, you can use
    :meth:`FFmpegOpusAudio.from_probe` to probe for bitrate and codec information.  This
    can be used to opportunistically skip pointless re-encoding of existing Opus audio data
    for a boost in performance at the cost of a short initial delay to gather the information.
    The same can be achieved by passing ``copy`` to the ``codec`` parameter, but only if you
    know that the input source is Opus encoded beforehand.

    .. versionadded:: 1.3

    .. warning::

        You must have the ffmpeg or avconv executable in your path environment
        variable in order for this to work.

    Parameters
    ----------
    source: Union[:class:`str`, :class:`io.BufferedIOBase`]
        The input that ffmpeg will take and convert to Opus bytes.
        If ``pipe`` is ``True`` then this is a file-like object that is
        passed to the stdin of ffmpeg.
    bitrate: :class:`int`
        The bitrate in kbps to encode the output to.  Defaults to ``128``.
    codec: Optional[:class:`str`]
        The codec to use to encode the audio data.  Normally this would be
        just ``libopus``, but is used by :meth:`FFmpegOpusAudio.from_probe` to
        opportunistically skip pointlessly re-encoding Opus audio data by passing
        ``copy`` as the codec value.  Any values other than ``copy``, ``opus``, or
        ``libopus`` will be considered ``libopus``.  Defaults to ``libopus``.

        .. warning::

            Do not provide this parameter unless you are certain that the audio input is
            already Opus encoded.  For typical use :meth:`FFmpegOpusAudio.from_probe`
            should be used to determine the proper value for this parameter.

    executable: :class:`str`
        The executable name (and path) to use. Defaults to ``ffmpeg``.
    pipe: :class:`bool`
        If ``True``, denotes that ``source`` parameter will be passed
        to the stdin of ffmpeg. Defaults to ``False``.
    stderr: Optional[:term:`py:file object`]
        A file-like object to pass to the Popen constructor.
        Could also be an instance of ``subprocess.PIPE``.
    before_options: Optional[:class:`str`]
        Extra command line arguments to pass to ffmpeg before the ``-i`` flag.
    options: Optional[:class:`str`]
        Extra command line arguments to pass to ffmpeg after the ``-i`` flag.

    Raises
    ------
    ClientException
        The subprocess failed to be created.
       NrD   F)bitratecodecrE   r   r   r   r   c               \   g }	|rt         j                  nt         j                  |d}
t        |t              r$|	j                  t        j                  |             |	j                  d       |	j                  |rdn|       |dv rdnd}|	j                  ddd	d
d|ddddd| dddf       t        |t              r$|	j                  t        j                  |             |	j                  d       t        | (  |f||	d|
 t        | j                        j                         | _        y )Nr   r   r   )opuslibopuscopyr   z-map_metadataz-1r   r   z-c:ar   r   r   r   z-b:akr   r   r   r   )rN   rO   r   rP   rQ   r   r   r   r   r   r:   r   rV   iter_packets_packet_iter)r    r^   r   r   rE   r   r   r   r   rJ   r_   rj   s              r!   r:   zFFmpegOpusAudio.__init__  s    (,Z__*2D2D

 nc*KKN34D4CV,#66I)1	
& gs#KKG,-HWJTWEVW%dll3@@Br#   )methodc                  K   |j                  d      }| j                  |||       d{   \  }} | |f||d|S 7 w)a  |coro|

        A factory method that creates a :class:`FFmpegOpusAudio` after probing
        the input source for audio codec and bitrate information.

        Parameters
        ----------
        source
            Identical to the ``source`` parameter for the constructor.
        method: Optional[Union[:class:`str`, Callable[:class:`str`, :class:`str`]]]
            The probing method used to determine bitrate and codec information. As a string, valid
            values are ``native`` to use ffprobe (or avprobe) and ``fallback`` to use ffmpeg
            (or avconv).  As a callable, it must take two string arguments, ``source`` and
            ``executable``.  Both parameters are the same values passed to this factory function.
            ``executable`` will default to ``ffmpeg`` if not provided as a keyword argument.
        kwargs
            The remaining parameters to be passed to the :class:`FFmpegOpusAudio` constructor,
            excluding ``bitrate`` and ``codec``.

        Returns
        -------
        :class:`FFmpegOpusAudio`
            An instance of this class.

        Raises
        ------
        AttributeError
            Invalid probe method, must be ``'native'`` or ``'fallback'``.
        TypeError
            Invalid value for ``probe`` parameter, must be :class:`str` or a callable.

        Examples
        --------

        Use this function to create an :class:`FFmpegOpusAudio` instance instead of the constructor: ::

            source = await discord.FFmpegOpusAudio.from_probe("song.webm")
            voice_client.play(source)

        If you are on Windows and don't have ffprobe installed, use the ``fallback`` method
        to probe using ffmpeg instead: ::

            source = await discord.FFmpegOpusAudio.from_probe("song.webm", method='fallback')
            voice_client.play(source)

        Using a custom method of determining codec and bitrate: ::

            def custom_probe(source, executable):
                # some analysis code here
                return codec, bitrate

            source = await discord.FFmpegOpusAudio.from_probe("song.webm", method=custom_probe)
            voice_client.play(source)
        rE   r   rE   N)r   r   )rM   probe)clsr^   r   ra   rE   r   r   s          r!   
from_probezFFmpegOpusAudio.from_probe  sO     ~ ZZ-
"yy:yVVw6B7%B6BB Ws   )A?Ar   c               T  K   |xs d}xs ddxt        |t              r;t        | d| d      t        d|      | j                  u rJ| j
                  n=t        |      r|| j
                  n#t        d|j                  j                   d      dx}}t        j                         }	 |j                  dfd       d{   \  }}t        j                  d	||       ||fS 7 "# t        $ r st        j!                  d
|       Y ||fS t        j!                  d|       	 |j                  dfd       d{  7  \  }}t        j                  d||       n%# t        $ r t        j!                  d       Y nw xY wY w xY w# ||fc cY S xY ww)aO  |coro|

        Probes the input source for bitrate and codec information.

        Parameters
        ----------
        source
            Identical to the ``source`` parameter for :class:`FFmpegOpusAudio`.
        method
            Identical to the ``method`` parameter for :meth:`FFmpegOpusAudio.from_probe`.
        executable: :class:`str`
            Identical to the ``executable`` parameter for :class:`FFmpegOpusAudio`.

        Returns
        -------
        Optional[Tuple[Optional[:class:`str`], Optional[:class:`int`]]]
            A 2-tuple with the codec and bitrate of the input source.

        Raises
        ------
        AttributeError
            Invalid probe method, must be ``'native'`` or ``'fallback'``.
        TypeError
            Invalid value for ``probe`` parameter, must be :class:`str` or a callable.
        nativerD   N_probe_codec_zInvalid probe method z5Expected str or callable for parameter 'probe', not ''c                             S r*   r%   )rE   	probefuncr^   s   r!   <lambda>z'FFmpegOpusAudio.probe.<locals>.<lambda>4  s    iPVXbFc r#   z Probe found codec=%s, bitrate=%szProbe '%s' using '%s' failedz-Probe '%s' using '%s' failed, trying fallbackc                             S r*   r%   )rE   fallbackr^   s   r!   r   z'FFmpegOpusAudio.probe.<locals>.<lambda>>  s    (SY[eJf r#   z)Fallback probe found codec=%s, bitrate=%sz Fallback probe using '%s' failed)rP   rQ   getattrAttributeError_probe_codec_native_probe_codec_fallbackcallablerR   rj   r3   asyncioget_event_looprun_in_executorrn   ro   rr   rs   )	r   r^   r   rE   r   r   loopr   r   s	    ` `   @@r!   r   zFFmpegOpusAudio.probe  s    D #8+8
##	Hfc"}VH%=tDI $'<VJ%GHHC33344fI00H((112!5 
 %%'	"#'#7#7>c#ddNE7  II8%I'>!% e 	W=vzR '>! NN?W'+';';DBf'g!g!gw 		EugV  OA:NO	W" '>!s   B1F(8C7 C5C7 F 1F(5C7 7"FF F(F6E1EE1F1FFFFF FF F%#F(c           	     8   |dv r|d d  dn|}|dddddd	d
| g	}t        j                  |d      }d x}}|rat        j                  |      }|d   d   }|j	                  d      }t        |j	                  dd            }t        t        |dz        d      }||fS )N>   avconvrD      r   z-vquietz-print_formatjsonz-show_streamsz-select_streamsza:0   timeoutstreamsr   
codec_namebit_ratei     )rN   check_outputr   loadsrM   r   maxround)	r^   rE   exerJ   outputr   r   r   
streamdatas	            r!   r   z#FFmpegOpusAudio._probe_codec_nativeH  s     11 "1~e$ 	 

 ((r:::f%Di+JNN<0E*..Q78G%$/5Gg~r#   c                   |dd| g}t        j                  |t        t         j                  t         j                        }|j                  d      \  }}|j                  d      }d x}}t        j                  d|      }	|	r|	j                  d      }t        j                  d	|      }
|
r$t        t        |
j                  d            d
      }||fS )Nz-hide_bannerr   )rd   rH   r   r   r   utf8zStream #0.*?Audio: (\w+)r
   z(\d+) [kK]b/sr   )rN   rf   r   rO   STDOUTru   decoderesearchgroupr   r   )r^   rE   rJ   rw   out_r   r   r   codec_matchbr_matchs              r!   r   z%FFmpegOpusAudio._probe_codec_fallbackj  s     ND&9*??$$	
 !!"!-QF#ii ;VD%%a(E99-v6#hnnQ/0#6Gg~r#   c                .    t        | j                  d      S r<   )nextr   r   s    r!   r"   zFFmpegOpusAudio.read  s    D%%s++r#   c                     y)NTr%   r   s    r!   r&   zFFmpegOpusAudio.is_opus  s    r#   )
r^   r   r   r   r   r   rE   rQ   r-   r2   )
r   ztype[FT]r^   rQ   r   @str | Callable[[str, str], tuple[str | None, int | None]] | Nonera   r   r-   r   )r^   rQ   r   r   rE   r   r-   tuple[str | None, int | None])rD   )rE   rQ   r-   r   r,   r/   )r3   r4   r5   r6   r:   classmethodr   r   staticmethodr   r   r"   r&   r   r   s   @r!   r   r   E  sZ   :@  "3C'3C 	3C
 3C 3C 
3Cj 
 TX	@C@C@C Q	@C
 @C 
@C @CD 
 TX!%K"K" Q	K"
 K" 
'K" K"Z "*	& B "*	& 0,r#   c                  b    e Zd ZdZdd	dZed
d       Zej                  dd       ZddZddZ	y)r   a  Transforms a previous :class:`AudioSource` to have volume controls.

    This does not work on audio sources that have :meth:`AudioSource.is_opus`
    set to ``True``.

    Parameters
    ----------
    original: :class:`AudioSource`
        The original AudioSource to transform.
    volume: :class:`float`
        The initial volume to set it to.
        See :attr:`volume` for more info.

    Raises
    ------
    TypeError
        Not an audio source.
    ClientException
        The audio source is opus encoded.
    c                    t        |t              s#t        d|j                  j                   d      |j                         rt        d      || _        || _        y )Nzexpected AudioSource not .z%AudioSource must not be Opus encoded.)	rP   r   rR   rj   r3   r&   r   originalvolume)r    r   r   s      r!   r:   zPCMVolumeTransformer.__init__  sU    (K078J8J8S8S7TTUVWW!"IJJ$r#   c                    | j                   S )zTRetrieves or sets the volume as a floating point percentage (e.g. ``1.0`` for 100%).)_volumer   s    r!   r   zPCMVolumeTransformer.volume  s     ||r#   c                &    t        |d      | _        y )Ng        )r   r   )r    values     r!   r   zPCMVolumeTransformer.volume  s    5#r#   c                8    | j                   j                          y r*   )r   r(   r   s    r!   r(   zPCMVolumeTransformer.cleanup  s    r#   c                    | j                   j                         }t        j                  |dt	        | j
                  d            S )Nr   g       @)r   r"   audioopmulminr   r@   s     r!   r"   zPCMVolumeTransformer.read  s2    mm  "{{33t||S#9::r#   N)g      ?)r   r   r   float)r-   r   )r   r   r-   r2   r1   r,   )
r3   r4   r5   r6   r:   propertyr   setterr(   r"   r%   r#   r!   r   r     sB    *   ]]' ' ;r#   r   c                      e Zd ZU ej                  dz  Zded<   ddddZddZddZ	dd	Z
dd
ZddddZddddZddZddZddZddZy)AudioPlayerg     @@r   DELAYN)afterc                  t         j                  j                  |        d| _        || _        || _        || _        t        j                         | _        t        j                         | _	        | j                  j                          d | _        |j                  | _        t        j                         | _        |t        |      st!        d      y y )NTz.Expected a callable for the "after" parameter.)rZ   r[   r:   rK   r^   clientr   Event_end_resumedset_current_error
_connectedLock_lockr   rR   )r    r^   r   r   s       r!   r:   zAudioPlayer.__init__  s    !!$' #)#)?D
%.__%6	)2):04+1+<+<%.^^%5
Xe_LMM &5r#   c                   d| _         t        j                         | _        | j                  j
                  }| j                  d       | j                  j                         st| j                  j                         s| j                  j                          P| j                  j                         s:| j                  j                          d| _         t        j                         | _        | xj                   dz  c_         | j                  j                         }|s| j                          y  ||| j                  j                                 | j                  | j                   | j                   z  z   }t#        d| j                   |t        j                         z
  z         }t        j$                  |       | j                  j                         ssy y )Nr   Tr
   )encode)loopstimeperf_counter_startr   send_audio_packet_speakr  is_setr  waitr  r^   r"   stopr&   r   r   sleep)r    
play_audior   	next_timedelays        r!   _do_runzAudioPlayer._do_run  sI   
'') [[22
D))""$=='')""$ ??))+$$&
"//1JJ!OJ;;##%D		t(;(;(=$=>djj4::&==I4::T5F5F5H)HIJEJJu3 ))""$$r#   c                2   	 | j                          | j                  j                          | j                          y # t        $ r!}|| _        | j                          Y d }~Pd }~ww xY w# | j                  j                          | j                          w xY wr*   )r  rr   r  r  r^   r(   _call_after)r    rl   s     r!   runzAudioPlayer.run  sr    	LLN
 KK!  	"%DIIKK	 KK!s'   = 	A'A"A* "A''A* *,Bc                   | j                   }| j                  	 | j                  |       y |rld| j                   }t        j	                  ||       t        |t        j                         t        j                  t        |      ||j                         y y # t        $ rP}t        j	                  d       ||_        t        j                  t        |      ||j                         Y d }~y d }~ww xY w)Nz"Calling the after function failed.zException in voice thread rz   )file)r  r   rr   rn   rs   __context__	tracebackprint_exceptiontype__traceback__rL   printsysr   )r    errorrl   msgs       r!   r  zAudioPlayer._call_after  s    ##::!M

5!
 .tyyk:CNN3N/#CJJ'%%d5k5%:M:MN	 	  MCD"'))$s)S#:K:KLLMs   B 	C4$AC//C4c                    | j                   j                          | j                  j                          | j                  d       y r   )r  r  r  r  r   s    r!   r  zAudioPlayer.stop  s+    		Er#   Tupdate_speakingc               `    | j                   j                          |r| j                  d       y y r   )r  clearr  r    r)  s     r!   pausezAudioPlayer.pause  s&    KK r#   c                   d| _         t        j                         | _        | j                  j                          |r| j                  d       y y )Nr   T)r  r  r  r  r  r  r  r,  s     r!   resumezAudioPlayer.resume  s=    
'')KK r#   c                p    | j                   j                         xr | j                  j                          S r*   )r  r  r  r   s    r!   
is_playingzAudioPlayer.is_playing  s*    }}##%@dii.>.>.@*@@r#   c                r    | j                   j                          xr | j                  j                          S r*   )r  r  r  r   s    r!   	is_pausedzAudioPlayer.is_paused   s-    99##%%Ddmm.B.B.D*DDr#   c                    | j                   5  | j                  d       || _        | j                  d       d d d        y # 1 sw Y   y xY w)NFr(  )r  r-  r^   r/  )r    r^   s     r!   _set_sourcezAudioPlayer._set_source#  sA    ZZ 	/JJuJ- DKKKK.	/ 	/ 	/s   ,AAc                    	 t        j                  | j                  j                  j	                  |      | j                  j
                         y # t        $ r }t        j                  d|       Y d }~y d }~ww xY w)Nz"Speaking call in player failed: %s)	r   run_coroutine_threadsafer   wsspeakr   rr   rn   ro   )r    speakinges      r!   r  zAudioPlayer._speak)  s[    	?,,$$X.0@0@  	?II:A>>	?s   AA 	A9A44A9)r^   r   r   r   r1   )r)  r0   r-   r2   r/   )r^   r   r-   r2   )r:  r0   r-   r2   )r3   r4   r5   r=   FRAME_LENGTHr   __annotations__r:   r  r  r  r  r-  r/  r1  r3  r5  r  r%   r#   r!   r   r     s`    ++f4E54JN N"!FO 
 04 
 15 AE/?r#   r   )2r6   
__future__r   r   r   ior   loggingr   r   rN   r$  rZ   r  r  typingr   r   r   r   r   r	   errorsr   oggparser   r   r   r=   utilsr   voice_clientr   r   r   	getLoggerr3   rn   __all__r=  platformr   r   r   r   r   r   r   r[   r   r%   r#   r!   <module>rI     s
  2 #   	   	   
    E E #  ( ) T'T*+w"  <<7!+ +\{ &m=+ m=`H[ HVBk BJ
.;; .;bt?)"" t?r#   