
    \
jx                        d 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 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 dd	lmZmZmZ dd
lmZmZmZ ddlT ddl m!Z!  G d d          Z" G d d          Z# G d d          Z$ G d de          Z% G d de          Z& G d de!          Z'd Z(d Z) G d d          Z*d Z+d Z,d  Z-d! Z.d" Z/d# Z0d$ Z1d% Z2d& Z3d' Z4d( Z5d) Z6d* Z7d+ Z8d, Z9d- Z:d. Z;d/ Z< G d0 d1          Z= G d2 d3e=          Z> G d4 d5e=          Z? G d6 d7e          Z@ e)             ejA        d8         rd9ZBnd:ZBeCD                    d;            G d< d=e          ZEd> ZFd? ZGdS )@z,Use ffmpeg to decode audio and video media.
    )deque)c_intc_int32c_uint8c_char_p	addressofbyrefcastPOINTER	Structurecreate_string_buffermemmoveN)image)asbytesasbytes_filenameasstr   )MediaDecoder)	AudioData
SourceInfoStaticSource)StreamingSourceVideoFormatAudioFormat)*   )MediaFormatExceptionc                       e Zd Zd ZdS )FileInfoc                     d | _         d | _        d | _        d| _        d| _        d| _        d| _        d| _        d | _        d| _	        d| _
        d S )N )	n_streams
start_timedurationtitleauthor	copyrightcommentalbumyeartrackgenreselfs    T/DATA/AppData/hermes/venv/lib/python3.11/site-packages/pyglet/media/codecs/ffmpeg.py__init__zFileInfo.__init__7   sS    

	



    N__name__
__module____qualname__r0    r1   r/   r   r   6   s#            r1   r   c                       e Zd Zd ZdS )StreamVideoInfoc                 h    || _         || _        || _        || _        || _        || _        || _        d S N)widthheightsample_aspect_numsample_aspect_denframe_rate_numframe_rate_dencodec_id)r.   r;   r<   r=   r>   r?   r@   rA   s           r/   r0   zStreamVideoInfo.__init__F   s;    
!2!2,, r1   Nr2   r6   r1   r/   r8   r8   E   s#        ! ! ! ! !r1   r8   c                       e Zd Zd ZdS )StreamAudioInfoc                 >    || _         || _        d | _        || _        d S r:   )sample_formatsample_ratesample_bitschannels)r.   rE   rF   rH   s       r/   r0   zStreamAudioInfo.__init__R   s%    *& r1   Nr2   r6   r1   r/   rC   rC   Q   s#        ! ! ! ! !r1   rC   c                   *    e Zd Zd ee          fgZdS )
FFmpegFilecontextN)r3   r4   r5   r   AVFormatContext_fields_r6   r1   r/   rJ   rJ   Y   s'        	GGO,,-HHHr1   rJ   c                   f    e Zd Zdefd ee          fd ee          fd ee          fdefgZ	dS )FFmpegStreamtypeformat_contextcodec_contextframe	time_baseN)
r3   r4   r5   r   r   rL   AVCodecContextAVFrame
AVRationalrM   r6   r1   r/   rO   rO   _   s[        		77?334	''.112	'''""#	j!HHHr1   rO   c                       e Zd ZdS )FFmpegExceptionNr3   r4   r5   r6   r1   r/   rY   rY   i           Dr1   rY   c                      | j         t          z   S )zVReturn the audio buffer size

    Buffer size can accomodate 1 sec of audio data.
    )bytes_per_secondFF_INPUT_BUFFER_PADDING_SIZE)audio_formats    r/   ffmpeg_get_audio_buffer_sizer`   m   s    
 (+GGGr1   c                      dS )zOInitialize libavformat and register all the muxers, demuxers and
    protocols.Nr6   r6   r1   r/   ffmpeg_initrb   u   s	     	Dr1   c                   "    e Zd ZdZdZd Zd ZdS )MemoryFileObjectz>A class to manage reading and seeking of a ffmpeg file object.i   c                     | _         d  _        d  _        t           j         dd           rt           j         dd           st	          d           j                             dd            j                                          _         j                             d            fd} fd}t          	                    |           _
        t                              |           _        d S )Nseektellz%File object does not support seeking.r   r   c                 |    j                             |          }t          |          }t          |||           |S r:   )filereadlenr   )_buffbuf_sizedata	read_sizer.   s        r/   read_data_cbz/MemoryFileObject.__init__.<locals>.read_data_cb   s9    9>>(++DD		ID$	***r1   c                 l    |t           j        k    rj        S j                            ||          }|S r:   )libavformatAVSEEK_SIZE	file_sizeri   rf   )rl   offsetwhenceposr.   s       r/   seek_data_cbz/MemoryFileObject.__init__.<locals>.seek_data_cb   s3    000~%)..00CJr1   )ri   fmt_contextbuffergetattr	Exceptionrf   rg   ru   rs   ffmpeg_read_func	read_funcffmpeg_seek_func	seek_func)r.   ri   rq   ry   s   `   r/   r0   zMemoryFileObject.__init__   s    	ty&$// 	Ewty&RV7W7W 	ECDDD 		q!))	q	 	 	 	 		 	 	 	 	 %55lCC$55lCCr1   c                     | j         r1	 t                              | j                    n# t          $ r Y nw xY w| j        r3	 t                              | j                   dS # t          $ r Y dS w xY wdS )z=These are usually freed when the source is, but no guarantee.N)r{   avutilav_freepOSErrorrz   r-   s    r/   __del__zMemoryFileObject.__del__   s    ; 	,,,,     	 011111   	 	s   ) 
66A" "
A0/A0N)r3   r4   r5   __doc__buffer_sizer0   r   r6   r1   r/   rd   rd   {   s@        HHKD D D:    r1   rd   c           	         t                      }t          j                                        |_        d|j        j        _        t          |          }t          j	        
                    |j                  }t          |t                    |_        t          |j                  }t          j                            |j        |j        d||j        d|j                  |_        |j        |j        j        _        |j        j        xj        t          j        z  c_        t                              t1          |j                  | dd          }|dk    r8t3          d|                     d          z   dz   t7          |          z             t                              |j        d          }|dk     rt3          d          ||fS )zOpen a media file from a file object.
    :rtype: FFmpegFile
    :return: The structure containing all the information for the media.
    r   r   NKavformat_open_input in ffmpeg_open_filename returned an error opening file utf8 Error code: Could not find stream info)rJ   rs   avformatavformat_alloc_contextrK   contentsseekablerd   	libavutilr   	av_mallocr   r
   r   r{   r   avio_alloc_contextr   r   rz   pbflagsAVFMT_FLAG_CUSTOM_IOavformat_open_inputr	   rY   decodestravformat_find_stream_info)filenamefile_objectri   memory_fileav_bufptrresults          r/   ffmpeg_open_memory_filer      s   
 <<D'>>@@DL%&DL"";//K''(?@@Ffh//K
{6
7
7C)2EE	 K  +6DLL;#CC))%*=*=xtTTF{{k ( 7 78 /025f++> ? ? 	? //dCCFzz:;;;r1   c                 f   t                      }t                              t          |j                  | dd          }|dk    r8t          d|                     d          z   dz   t          |          z             t                              |j        d          }|dk     rt          d          |S )zzOpen the media file.

    :rtype: FFmpegFile
    :return: The structure containing all the information for the media.
    Nr   r   r   r   r   )	rJ   r   r   r	   rK   rY   r   r   r   )r   ri   r   s      r/   ffmpeg_open_filenamer      s     <<D))%*=*=*2*.*.0 0F
 {{k ( 7 78 /025f++> ? ? 	? //dCCFzz:;;;Kr1   c                 ^    t                               t          | j                             dS )z(Close the media file and free resources.N)r   avformat_close_inputr	   rK   )ri   s    r/   ffmpeg_close_filer      s&    !!%"5"566666r1   c                    t                      }| j        j        j        |_        | j        j        j        |_        | j        j        j        |_        t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d          dd          p8t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d	          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d
          dd          }|rt          |j        j                  |_        t                              | j        j        j	        t          d          dd          }|rt          |j        j                  |_        |S )zGet information on the file:

        - number of streams
        - duration
        - artist
        - album
        - date
        - track

    :rtype: FileInfo
    :return: The file info instance containing all the meta information.
    r%   Nr   artistalbum_artistr'   r(   r)   dater+   r,   )r   rK   r   
nb_streamsr"   r#   r$   r   av_dict_getmetadatar   r   valuer%   r&   r'   r(   r)   r*   r+   r,   )ri   infoentrys      r/   ffmpeg_file_infor      s    ::D\*5DNl+6DOL)2DMt|4=ww?O?OQUWXYYE 15>/00
t|4=wx?P?PRVXYZZ `dl3<gn>U>UW[]^__ 
 2EN011t|4=w{?S?SUY[\]]E 5u~344t|4=wy?Q?QSWYZ[[E 3U^122t|4=ww?O?OQUWXYYE 15>/00
t|4=wvPTVWXXE 0%..//	t|4=ww?O?OQUWXYYE 15>/00
t|4=ww?O?OQUWXYYE 15>/00
Kr1   c           	         | j         j        j        |         j        }|j        j        }|j        t
          k    rt          rt          d|j                   t          d|j                   t          dt          
                    |j                                      d                     t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d	|j                   t          d
|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j        j        |j        j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                   t          d|j                    t          d|j!                   t          d|j"                   t          d|j#                   t          d|j$                   t          d|j%                   t          d|j&                   t          d|j'                   t          d|j(                   tR          *                    | j         |d           }tW          |j        |j        |j        j        |j        j        |j        |j        |j                  }n|j        tX          k    rt[          |j        |j#        |j"                  }|j        t\          t^          fv rd!|_0        nW|j        tb          td          tf          th          fv rd"|_0        n.|j        tj          tl          fv rd#|_0        nd |_7        d |_0        nd S |S )$zOpen the stream
    zcodec_type=z
 codec_id=z codec name=utf-8z codec_tag=z extradata=z extradata_size=z format=z
 bit_rate=z bits_per_coded_sample=z bits_per_raw_sample=z	 profile=z level=z width=z height=z sample_aspect_ratio=z field_order=z color_range=z color_primaries=z color_trc=z color_space=z chroma_location=z video_delay=z channel_layout=z
 channels=z sample_rate=z block_align=z frame_size=z initial_padding=z trailing_padding=z seek_preroll=N          )8rK   r   streamscodecpar
codec_typeAVMEDIA_TYPE_VIDEO_debugprintrA   avcodecavcodec_get_namer   	codec_tag	extradataextradata_sizeformatbit_ratebits_per_coded_samplebits_per_raw_sampleprofilelevelr;   r<   sample_aspect_rationumdenfield_ordercolor_rangecolor_primaries	color_trccolor_spacechroma_locationvideo_delaychannel_layoutrH   rF   block_align
frame_sizeinitial_paddingtrailing_paddingseek_prerollr   av_guess_frame_rater8   AVMEDIA_TYPE_AUDIOrC   AV_SAMPLE_FMT_U8AV_SAMPLE_FMT_U8PrG   AV_SAMPLE_FMT_S16AV_SAMPLE_FMT_S16PAV_SAMPLE_FMT_FLTAV_SAMPLE_FMT_FLTPAV_SAMPLE_FMT_S32AV_SAMPLE_FMT_S32PrE   )ri   stream_index	av_streamrK   
frame_rater   s         r/   ffmpeg_stream_infor   *  s    %-l;DI )G/// 	:-!3444, 0111.'":":7;K"L"L"S"ST["\"\]]]-!2333-!2333$g&<===*gn---, 0111+W-JKKK)7+FGGG+w///)W]+++)W]+++*gn---)7+F+JGLgLklll/7#6777/7#6777%w'>???-!2333/7#6777%w'>???/7#6777$g&<===, 0111/7#6777/7#6777.'"4555%w'>???&(@AAA"G$899911$,	4PP
MN'+'+NN
 
 
	1	1	1N
 

 >.0ABBB D^ 13E 13E G G G!D^ 13EFFF!D!%D#DtKr1   c                    d|cxk    r| j         j        j        k     s3n t          d                    | j         j        j                            t
                              d           }|st          d          t
                              || j         j        j	        |         j        j
                  }|dk     r6t
                              t          |                     t          d          |j        j        }t
                              |          }t          r.t!          d|d|j        j                                                   |t&          k    r1t
                              d                    d                    }|p|}|t,          k    r1t
                              d	                    d                    }|p|}|s"t          d
                    |                    |j        j        }t          r,t!          d|j        j                                                   t
                              ||d           }|dk     rt          d          t3                      }| j         |_        ||_        |j        j        |_        t<                                          |_         | j         j        j	        |         j        j!        |_!        |S )Nr   z$index out of range. Only {} streams.z!Could not allocate Codec Context.z"Could not copy the AVCodecContext.zFound Codec==z
libvpx-vp9r   libvpxz)No codec found for this media. codecID={}zLoaded codec: z(Could not open the media with the codec.)"rK   r   r   rY   r   r   avcodec_alloc_context3MemoryErroravcodec_parameters_to_contextr   r   avcodec_free_contextr	   rA   avcodec_find_decoderr   r   	long_namer   AV_CODEC_ID_VP9avcodec_find_decoder_by_nameencodeAV_CODEC_ID_VP8idavcodec_open2rO   rQ   rR   r   rP   r   av_frame_allocrS   rT   )ri   indexrR   r   rA   codecnewcodecstreams           r/   ffmpeg_open_streamr   q  s   8888-88888DKKDLLaLlmmnnn22488M ?=>>>22%e,5>@ @F zz$$U=%9%9:::BCCC%.H((22E PnhU^-E-L-L-N-NOOO ?""778K8KG8T8TUU!E?""778P8PQQ!E = ++16(+;+;= = 	= ~ H C 8 ? ? A ABBB""=%>>FzzHIII^^F LF(F(3FK((**FL|,4U;DNFMr1   c                     | j         r,t                              t          | j                              t                              t          | j                             d S r:   )rS   r   av_frame_freer	   r   r   rR   )r   s    r/   ffmpeg_close_streamr     sO    | 2U6<00111  v';!<!<=====r1   c                 <   d}| j         j        j        t          z  }t                              | j         dd|||          }|dk     rVt          d          }t                              ||d           |j	        }t          d|                                z             d S )Nr      zError occured while seeking. )rK   r   r$   AV_TIME_BASEr   avformat_seek_filer   r   av_strerrorr   rY   r   )ri   	timestampr   max_tsr   bufdescrs          r/   ffmpeg_seek_filer	    s    E\"+l:F((b!9e F zz"3''63,,,	=#llnn- . . 	.	 zr1   c                     t                               |           t                              | j        |          }|dk     rdS dS )zRead from the stream a packet.

    :rtype: bool
    :return: True if the packet was correctly read. False if the end of stream
        was reached or an error occured.
    r   FT)r   av_packet_unrefr   av_read_framerK   )ri   packetr   s      r/   ffmpeg_readr    sB     F#####DL&99Fzzu4r1   c                     |j         j        t          k    r|j         j        }nd}t                              || j        j         j        |j         j                 j         j        t                    }|S Nr   )
r   dtsAV_NOPTS_VALUEr   av_rescale_qrK   r   r   rT   AV_TIME_BASE_Q)ri   r  ptsr  s       r/   ffmpeg_get_packet_ptsr    sc    n,,o!##C$(L$9$A(.(D%FFNy$24 4I r1   c                 t    | j         j        j        }t                              || j        t                    }|S r:   )rS   r   best_effort_timestampr   r  rT   r  )r   tsr  s      r/   ffmpeg_get_frame_tsr    s7    			4B##B$*$4$24 4I r1   c                  Z    t                                           } | st          d          | S )NzCould not allocate AVPacket.)r   av_packet_allocr   )ps    r/   ffmpeg_init_packetr    s/    !!A :8999Hr1   c                 T    t                               t          |                      d S r:   )r   av_packet_freer	   r  s    r/   ffmpeg_free_packetr"    s"    5==)))))r1   c                 T    t                               t          |                      d S r:   )r   r  r	   r!  s    r/   ffmpeg_unref_packetr$    s"    E&MM*****r1   c                 <    t                               | |           d S r:   )r   av_packet_move_ref)dstsrcs     r/   ffmpeg_transfer_packetr)    s    sC(((((r1   c                  X    t                                                                           S )z.Return an informative version string of FFmpeg)r   av_version_infor   r6   r1   r/   get_versionr,    s     !!##**,,,r1   c                 &    t          |           dz  S Ni@B )floatr  s    r/   timestamp_from_ffmpegr1    s    g%%r1   c                 &    t          | dz            S r.  )intr0  s    r/   timestamp_to_ffmpegr4    s    y7"###r1   c                       e Zd Zd Zd ZdS )_Packetc                 ~    t                      | _        t          t          | j                  |           || _        d S r:   )AVPacketr  r)  r	   r  )r.   r  r  s      r/   r0   z_Packet.__init__  s2    jjuT[116:::"r1   c                 @    t           t          | j                   d S d S r:   )r$  r  r-   s    r/   r   z_Packet.__del__  s&    *,,,,, +*r1   N)r3   r4   r5   r0   r   r6   r1   r/   r6  r6    s2        # # #
- - - - -r1   r6  c                   "     e Zd ZdZ fdZ xZS )VideoPacketr   c                     t          t          |                               ||           d| _        | j        | _        t          xj        dz  c_        d S )Nr   r   )superr;  r0   r   _next_idr   )r.   r  r  	__class__s      r/   r0   zVideoPacket.__init__	  sM    k4  ))&)<<<
-!r1   )r3   r4   r5   r>  r0   __classcell__)r?  s   @r/   r;  r;    s=        H" " " " " " " " "r1   r;  c                       e Zd ZdS )AudioPacketNrZ   r6   r1   r/   rB  rB    r[   r1   rB  c                       e Zd ZdZdZddZd Zd Zd Zd Z	d	 Z
d
 Zd Zd Zd ZddZd Zd Zd Zd Zd ZddZd Zed             Zej        d             ZdS )FFmpegSource
   d   Nc                 $   d | _         d | _        d | _        d| _        d | _        d | _        |r+t          t          |          |          \  | _        | _        n!t          t          |                    | _        | j        s"t          d
                    |                    d | _        d | _        d | _         t          t                                | _         t          t"                                | _        t'          | j                  }t)                      | _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        t=          |j                  D ]}tA          | j        |          }tC          |tD                    r| j        tG          | j        |          }tI          |j%        |j&                  | _'        |j(        dk    r&tS          |j(                  |j*        z  | j'        _+        tS          |j,                  |j-        z  | j'        _.        || _        || _        tC          |t^                    r|j0        dv r| j        tG          | j        |          }tc          te          d|j3                  |j0        |j4                  | _5        || _        || _        tl          7                    |j3                  }te          d|j3                  }tl          7                    |          }	|j8        j9        j4        }
|j8        j9        j:        }|tv          tx          fv rtv          | _=        nf|t|          t~          fv rt|          | _=        nI|t          t          fv rt          | _=        n,|t          t          fv rt|          | _=        nt          d          t          E                    d |	| j=        |
|||
dd 	  	        | _        | j        r#t          F                    | j                  dk     r.t          G                    | j                   t          d	          t                      | _         g | _I        t                      | _K        | jL        | _M        | j5        r*t          | j5                  }t          |z              | _P        t                      | _Q        | jL        | _R        | S                                | _T        t          |jV                  | _W        | xjW        | jT        z  c_W        d| _X        | Y                                 | jT        dk    r| Z                    d
           d S d S )NFzCould not open "{0}")r;   r<   r   )r   r      r   )rH   sample_sizerF   zAudio format not supported.z$Cannot create sample rate converter.        )[_packet_video_stream_audio_stream_stream_end_file_memory_filer   r   r   rY   r   _video_stream_index_audio_stream_index_audio_formatr   
SwsContextimg_convert_ctx
SwrContextaudio_convert_ctxr   r   r   r%   r&   r'   r(   r)   r*   r+   r,   ranger"   r   
isinstancer8   r   r   r;   r<   video_formatr=   r/  r>   sample_aspectr?   r@   r   rC   rG   r   minrH   rF   r_   r   av_get_default_channel_layoutrR   r   
sample_fmtr   r   
tgt_formatr   r   r   r   r   r   
swresampleswr_alloc_set_optsswr_initswr_freer  _eventsr   audioqMAX_QUEUE_SIZE_max_len_audioqr`   r   _audio_buffervideoq_max_len_videoq_get_start_timer#   r1  r$   	_duration_fillq_scheduled_fillqrf   )r.   r   ri   	file_infoir   r   channel_inputchannels_outchannel_outputrF   rE   nbytess                r/   r0   zFFmpegSource.__init__  s   !! 
  	J,CDTU]D^D^`d,e,e)DJ))-.>x.H.HIIDJz 	K!"8"?"?"I"IJJJ#' #' !2wz2244!4!4!4!6!6$TZ00	LL	#/	$+	'1	%-	#/	"	#/	#/	 y*++ 8	R 8	RA%dj!44D$00 5RT5G5O+DJ::$/*;%( %( %(! )Q..!$"899 23 %3 d122+, !, &,"+,((D/22 %Rt7G;7V7V[_[m[u+DJ::$/ DM22 $ 0 $ 0%2 %2 %2! &,"+,( & D DT] S S"1dm44!'!E!El!S!S$2;G & 4 = H %57H$III&6DOO"'8:L&MMM&7DOO"'8:L&MMM&7DOO"'8:L&MMM&7DOO)*GHHH)3)F)FtGUGKXcGTVcGRGH$*P *P& . R"++D,BCCaGG''(>???)*PQQQ)++gg#2 	7243DEEV#*V#3"6"6Tgg#2..00.y/ABB$/) !&
 ?QIIcNNNNN r1   c                    | j         rt          t          | j                    | j        r:t          3t                              | j                   t          | j                   | j        r3t          	                    | j
                   t          | j                   | j        rt          t          | j                   d S d S d S r:   )rK  r"  rL  swscalesws_freeContextrU  r   rM  r`  rc  rW  rO  r   r-   s    r/   r   zFFmpegSource.__del__  s    < 	-.:t|,,, 	4'"5##D$8999 2333 	4 6777 2333: 	*+7dj)))))	* 	*77r1   c                 r   t           rt          d|           t          | j        t	          || j        z                        | j        d d = d| _        |                                  | 	                                 | j
        sbt          | j                  dk    rH|| j        d         j        k     rd S |                     d           t          | j                  dk    Fd S d S | j        s`t          | j                  dk    rF|| j        d         j        k     rd S |                                  t          | j                  dk    Dd S d S t          | j                  dk    rt          | j                  dk    r| j        d         j        | j        d         j        k     }|| j        d         j        k     }|| j        d         j        k     }|r|s|                                  n|s|                     d           nd S t          | j                  dk    rt          | j                  dk    d S d S d S d S )NzFFmpeg seekFr   )skip_empty_framer   )r   r   r	  rO  r4  r#   rd  rN  _clear_video_audio_queuesrn  r_   rk   ri  r  get_next_video_framerZ  re  _get_audio_packet)r.   r  audioq_is_firstcorrect_audio_poscorrect_video_poss        r/   rf   zFFmpegSource.seek  sd    	,-+++J	DO ;<<	
 	
 	
 LO &&(((   #	dk""Q&& t{1~777E--u-EEE dk""Q&&&&&& " 	dk""Q&& t{1~777E**,,, dk""Q&&&&&& dk""Q&&3t{+;+;a+?+? #'+a.":T[^=U"U$-A0H$H!$-A0H$H!" +< **,,,,* --u-EEEE E dk""Q&&3t{+;+;a+?+?+?+?&&+?+?&&r1   c                       j                                         }                                 }|s1 j        s*t          j                             fdd           d _        |S )zTake an audio packet from the queue.

        This function will schedule its `_fillq` function to fill up
        the queues if space is available. Multiple calls to this method will
        only result in one scheduled call to `_fillq`.
        c                 ,                                     S r:   rn  dtr.   s    r/   <lambda>z0FFmpegSource._get_audio_packet.<locals>.<lambda>      $++-- r1   r   T)re  popleft_check_low_levelrm  pygletclockschedule_once)r.   
audio_datalow_lvls   `  r/   r|  zFFmpegSource._get_audio_packet  sk     [((**
'')) 	)t4 	)L&&'?'?'?'?CCC$(D!r1   c                       j         sdS  j                                         }                                 }|s1 j        s*t          j                             fdd           d _        |S )zTake a video packet from the queue.

        This function will schedule its `_fillq` function to fill up
        the queues if space is available. Multiple calls to this method will
        only result in one scheduled call to `_fillq`.
        Nc                 ,                                     S r:   r  r  s    r/   r  z0FFmpegSource._get_video_packet.<locals>.<lambda>  r  r1   r   T)ri  r  r  rm  r  r  r  )r.   video_packetr  s   `  r/   _get_video_packetzFFmpegSource._get_video_packet  sz     { 	4{**,,'')) 	)t4 	)L&&'?'?'?'?CCC$(D!r1   c                 j    | j                                          | j                                         dS )z"Empty both audio and video queues.N)re  clearri  r-   s    r/   rz  z&FFmpegSource._clear_video_audio_queues  s0    r1   c                 l   d| _         t          | j                  | j        k     rt          | j                  | j        k     rp|                                 r|                                  n	d| _        dS t          | j                  | j        k     r#t          | j                  | j        k     ldS dS dS dS )zAFill up both Audio and Video queues if space is available in bothFTN)	rm  rk   re  rg  ri  rj  _get_packet_process_packetrN  r-   s    r/   rn  zFFmpegSource._fillq  s     !&4;$"6664;$"666!! $$&&&&#'  4;$"6664;$"66666 7666 76r1   c                    t          | j                  dk     st          | j                  dk     rPt          | j                  | j        k     r1t          | j                  | j        k     r|                                  dS dS )a  Check if both audio and video queues are getting very low.

        If one of them has less than 2 elements, we fill the queue immediately
        with new packets. We don't wait for a scheduled call because we need
        them immediately.

        This would normally happens only during seek operations where we
        consume many packets to find the correct timestamp.
        r   TF)rk   re  ri  rg  rj  rn  r-   s    r/   r  zFFmpegSource._check_low_level  ss     t{a3t{#3#3a#7#74;$"6663t{;K;KdNb;b;b4ur1   c                 6    t          | j        | j                  S r:   )r  rO  rK  r-   s    r/   r  zFFmpegSource._get_packet  s     4:t|444r1   c                    t          | j        | j                  }t          |          }|| j        z  }| j        j        j        | j        k    rVt          | j        |          }t          rt          d|j        |j        fz             | j                            |           |S | j        rK| j        j        j        | j        k    r3t#          | j        |          }| j                            |           |S dS dS )zProcess the packet that has been just read.

        Determines whether it's a video or audio packet and queue it in the
        appropriate queue.
        z!Created and queued packet %d (%f)N)r  rO  rK  r1  r#   r   r   rQ  r;  r   r   r   r  ri  appendr_   rR  rB  re  )r.   r  r  audio_packets       r/   r  zFFmpegSource._process_packet  s     *$*dlCC	))44	T_$	< -1III&t|Y??L g9\_lNd<eefffK|,,, 	 4<#8#EIa#a#a&t|Y??LK|,,,		  	 #a#ar1   rJ  c                    d}dx}}t          |          |k     rQ| j        snI|                                 }|                     ||          \  }}}|sn||z  }t          |          |k     Q|s&| j        s| j        st
          rt          d           d S t          |t          |          ||g           }| j        r| j        d         j	        ||z   k    ro| j        
                    d          }	|	j	        |k    r*|	xj	        |z  c_	        |j                            |	           | j        r| j        d         j	        ||z   k    ot
          rBt          d                    |j	        |j                             t          d| j                   |S )Nr1   r   z,Audio queue was starved by the audio driver.z/get_audio_data returning ts {0} with events {1}zremaining events are)rk   re  r|  _decode_audio_packetrN  r   r   r   rd  r  popeventsr  r   )
r.   	num_bytescompensation_timero   r  r$   r  r{   r  events
             r/   get_audio_datazFFmpegSource.get_audio_data5  s     	H$ii)##; 1133L*.*C*CLRc*d*d'FIx FND $ii)##  	DK 	# J JHIII4tSYY	8RHH
l 	0t|A8Y=QRRL$$Q''E)++9,!((///	 l 	0t|A8Y=QRR  	8CJJ:K_akarssttt($,777r1   c                    	 	 |                      |j        | j        |          }n# t          $ r Y nw xY w|dk    rnt	          |          }t          || j        t          |                     |j        }t          t          |                    | j	        j
        z  }t          | j                  }t          |          }|||fS dS )NTr   )Nr   r   )_ffmpeg_decode_audior  rh  rY   r   r   rk   rawr/  r_   r]   r  rM  r1  )r.   r  r  size_outr{   r$   r  s          r/   r  z!FFmpegSource._decode_audio_packet[  s    	/44 '&%' ' #    1}})(33FFD.F<<<ZFS[[))D,=,NNH+D,>??I-i88I9h..zs   !% 
22c                    | j         }|j        t          k    rt          d          t                              |j        |          }|dk     rft          d          }t          	                    ||d           |j
        }t          d                    |                                                    t                              |j        |j                  }|dk     rft          d          }t          	                    ||d           |j
        }t          d                    |                                                    t          d          }	t                              t#          |	          |j        j        j        |j        j        j        |j        j        j        d          }
|
dk     rt          d          t-          | j                  |
k     rt          d          |j        j        j        }|j        j        j        }t                              | j                  }t7          d	| j        j                  }|||z  z   }|d
| j        z
  z  d
z  }|d
| j        z   z  d
z  }t7          t=          ||          |          }t?          |          }||k    r9t@          !                    | j"        ||z
  |          }|dk     rt          d          |j        j        j#        }tI          |tK          tL                              }t@          '                    | j"        |          }t@          (                    | j"        t#          |          |||          }	 ||z  |z  }tI          tS          |j                  |z   tK          tL                              }t@          (                    | j"        t#          |          ||z
  d d          }|dk    rn||z  }||z  |z  }|S )Nz-Trying to decode audio on a non-audio stream.r   r  z,Error occurred sending packet to decoder. {}z"Error occurred receiving frame. {}r   z#Error in av_samples_get_buffer_sizez9Output audio buffer is too small for current audio frame!r   rF  zswr_set_compensation failed.)*rM  rP   r   rY   r   avcodec_send_packetrR   r   r   r  r   r   r   avcodec_receive_framerS   r   av_samples_get_buffer_sizer	   r   rH   
nb_samplesr^  rk   rh  rF   av_get_bytes_per_sampler_  r\  r_   SAMPLE_CORRECTION_PERCENT_MAXmaxr3  r`  swr_set_compensationrW  extended_datar
   r   r   swr_get_out_samplesswr_convertr   )r.   r  data_outr  r   sent_resultr  r  receive_result
plane_size	data_sizer  rF   bytes_per_samplerr  wanted_nb_samplesmin_nb_samplesmax_nb_samplesresdata_in
p_data_outout_samplestotal_samples_outrv   p_data_offsetsamples_outr  s                              r/   r  z!FFmpegSource._ffmpeg_decode_audios  s   #;,,,!"QRRR11 
 

 ??&s++C{C555IE!"P"W"WX]XdXdXfXf"g"ghhh 66 L
 

 A&s++C~sC888IE!"F"M"Mellnn"]"]^^^1XX
55* )2L!, )4 	 q==!"GHHHt!""Y..!"]^^^\*5
*3?!99$/JJ1d/899&):[)HH$d.P(PQTWW$d.P(PQTWW$5~ F FWW 122
**11&"Z/! C Qww%&DEEE,'5(GG$4$455
 44T5KZXX&2243I383D3Dk3:JH H	- (,69IIF *-..7   M %001G16}1E1E1<?P1PRVXY[ [K a,	-  &47GGr1   c                    | j         j        }| j         j        }|dz  }||z  t          z   }t	          |z              }	 |                     |j        |          }t          j        ||d||          }t          | j
                  }	t          |	          }	|	| j        z
  |_        n# t          $ r d }Y nw xY w||_        t          rt!          d||j                   d S d S )N   RGBAz"Decoding video packet at timestamp)rZ  r;   r<   r^   r   _ffmpeg_decode_videor  r   	ImageDatar  rL  r1  r#   r  rY   r   r   )
r.   r  r;   r<   pitchrt  r{   r   
image_datar  s
             r/   _decode_video_packetz!FFmpegSource._decode_video_packet  s    !'")	&.#??F"%%		A..|/B/57 7F
 NNJ+D,>??I-i88I%.%@L""  	 	 	JJJ	 ( 	^6lF\]]]]]	^ 	^s   B# #B21B2c                    | j         } t          t                    dz              }t          dz              }|j        j        j        }|j        j        j        }|j        t          k    rt          d          t                              |j        |          }|dk     rft          d          }	t                              ||	d           |	j        }
t          d                    |
                                                    t                              |j        |j                  }|dk     rft          d          }	t                              ||	d           |	j        }
t          d                    |
                                                    t                              |||t,          ||d           t.                              | j        |||j        j        j        ||t,          t6          d d d           | _        t.                              | j        t;          |j        j        j        t          t          t                                        |j        j        j        d|||           |S )Nr  z-Trying to decode video on a non-video stream.r   r  z3Video: Error occurred sending packet to decoder. {}z)Video: Error occurred receiving frame. {}r   ) rL  r   r   r   rR   r   r;   r<   rP   r   rY   r   r  r   r   r  r   r   r   r  rS   av_image_fill_arraysAV_PIX_FMT_RGBArv  sws_getCachedContextrU  pix_fmtSWS_FAST_BILINEAR	sws_scaler
   ro   linesize)r.   r  r  r   	rgba_ptrsrgba_strider;   r<   r  r  r  r  s               r/   r  z!FFmpegSource._ffmpeg_decode_video  s>   #)WW%%),,	qymm$-3%.5;,,,!"QRRR11 
 

 ??&s++C{C555IE!"W"^"^_d_k_k_m_m"n"nooo 66 L
 

 A&s++C~sC888IE!"M"T"TUZUaUaUcUc"d"deee##I{H$3UFA	G 	G 	G  ';; 66/8@6?tT4	 1  1 	$.v|49&ww'7'788: : ,/8 #%	' 	' 	' r1   c                 r   | j         sd S d }| j        r	 	 | j                                        }n# t          $ r Y nbw xY w|j        dk    r|                     |           |j        "|j        }| j                            |           n|                                  nd }t          rt          d|           |S )NTr   zNext video timestamp is)rZ  ri  r  
IndexErrorr   r  r  
appendleftr  r   r   )r.   r  r  s      r/   get_next_video_timestampz%FFmpegSource.get_next_video_timestamp#  s      	F; 	)#';#6#6#8#8LL!   E%**--l;;;%1%/BK**<888&&((() B 	1+R000	s   / 
<<Tc                     | j         sd S 	 |                                 }|sd S |j        dk    r|                     |           |j        |snCt          rt          d|           |j        S )NTr   	Returning)rZ  r  r   r  r   r   )r.   ry  r  s      r/   r{  z!FFmpegSource.get_next_video_frame?  s      	F		  1133L t!Q&&)),777!-5E-		  	-+|,,,!!r1   c                 T      fd}d }t           | |                                S )Nc               3      K   j         j        } j        j        fD ] }|| j        j        |         j        }|V  !d S r:   )rO  rK   rQ  rR  r   r   )rQ   idxr   r.   s      r/   r   z-FFmpegSource._get_start_time.<locals>.streamsT  s[      !Z/N0$2JK  ;'08=F	 r1   c              3      K   dV  | D ]Q}|j         }|t          k    rdV  t                              ||j        t
                    }t          |          }|V  Rd S r  )r#   r  r   r  rT   r  r1  )r   r   startr#   s       r/   start_timesz1FFmpegSource._get_start_time.<locals>.start_times\  s      GGG! ! !)N**GGG#00171A1?A A
 3:>>
     ! !r1   )r  )r.   r   r  s   `  r/   rk  zFFmpegSource._get_start_timeS  sK    	 	 	 	 	
	! 
	! 
	! ;;wwyy))***r1   c                     | j         S r:   )rS  r-   s    r/   r_   zFFmpegSource.audio_formatj  s    !!r1   c                 N    || _         || j                                         d S d S r:   )rS  re  r  )r.   r   s     r/   r_   zFFmpegSource.audio_formatn  s0    "=K =r1   r:   )rJ  T)r3   r4   r5   r  rf  r0   r   rf   r|  r  rz  rn  r  r  r  r  r  r  r  r  r  r{  rk  propertyr_   setterr6   r1   r/   rD  rD    s       $&! Nx x x xt
* 
* 
*2 2 2h        

 
 
   5 5 5
     2$ $ $ $L  0W W Wr^ ^ ^J0 0 0d  8" " " "(+ + +. " " X"          r1   rD  debug_mediaTFr   c                       e Zd Zd ZddZdS )FFmpegDecoderc                     dS )N)z.mp3z.oggr6   r-   s    r/   get_file_extensionsz!FFmpegDecoder.get_file_extensions  s    ~r1   Tc                 `    |rt          ||          S t          t          ||                    S r:   )rD  r   )r.   ri   r   	streamings       r/   r   zFFmpegDecoder.decode  s2     	>$///Xt < <===r1   Nr  )r3   r4   r5   r  r   r6   r1   r/   r  r    s7          > > > > > >r1   r  c                       t                      gS r:   )r  r6   r1   r/   get_decodersr    s    OOr1   c                      g S r:   r6   r6   r1   r/   get_encodersr    s    Ir1   )Hr   collectionsr   ctypesr   r   r   r   r   r	   r
   r   r   r   r   r  
pyglet.libr   pyglet.utilr   r   r   r!   r   baser   r   r   r   r   r   
ffmpeg_lib
exceptionsr   r   r8   rC   rJ   rO   rY   r`   rb   rd   r   r   r   r   r   r   r   r	  r  r  r  r  r"  r$  r)  r,  r1  r4  r6  r;  rB  rD  optionsr   r   av_log_set_levelr  r  r  r6   r1   r/   <module>r     s  H       _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _            8 8 8 8 8 8 8 8 8 8       5 5 5 5 5 5 5 5 5 5 ; ; ; ; ; ; ; ; ; ;     - - - - - -       	! 	! 	! 	! 	! 	! 	! 	!! ! ! ! ! ! ! !           9   	 	 	 	 	* 	 	 	H H H	 	 	- - - - - - - -`) ) )X  07 7 7
3 3 3lD D DN. . .b> > >. . .  
 
 
    * * *+ + +) ) )- - -
& & &$ $ $- - - - - - - -" " " " "' " " "	 	 	 	 	' 	 	 	]	  ]	  ]	  ]	  ]	 ? ]	  ]	  ]	 @ 	>-  FFF
A	> 	> 	> 	> 	>L 	> 	> 	>      r1   