
    ^j                       d Z ddlmZ ddl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 ddlmZ ddl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 dd
l m!Z!m"Z" ddl#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z.m/Z/m0Z0m1Z1m2Z2m3Z3m4Z4m5Z5m6Z6m7Z7 ddl8m9Z9m:Z:m;Z;m<Z< ddl=m>Z>m?Z?m@Z@mAZAmBZBmCZCmDZDmEZEmFZFmGZGmHZHmIZImJZJmKZKmLZLmMZMmNZNmOZO ddlPmQZQmRZR erddl8mSZS  G d d          ZTe G d d                      ZUe G d d                      ZV G d de	          ZW G d de	          ZX G d de          ZYd ZZd  Z[ G d! d"          Z\dYd)Z]dZd*Z^d[d,Z_d\d-Z`d]d1Zad^d3Zbd_d6Zcd`d9Zddad=Zedbd>Zfdcd?Zgddd@ZhdA ZidB ZjdC ZkdD ZldE ZmdF Zn G dG dH          Zo G dI dJeo          Zp G dK dLeo          Zq G dM dNe*          Zr e[             ejs        dO         rdPZtndQZt eOju        dR            G dS dTe$          ZvdedVZwdfdXZxdS )gz+Use ffmpeg to decode audio and video media.    )annotationsN)deque)POINTERArray	Structure_Pointer	addressofbyrefc_char_pc_intc_int32c_uint8castcreate_string_buffermemmove)	dataclass)TYPE_CHECKINGBinaryIOIteratorSequence)image)MediaFormatException)asbytesasstr   )MediaDecoder)	AudioDataAudioFormat
SourceInfoStaticSourceStreamingSourceVideoFormat)AV_CODEC_ID_VP8AV_CODEC_ID_VP9AV_INPUT_BUFFER_PADDING_SIZESWS_FAST_BILINEARAVPacket
SwrContext
SwsContextavcodeclibavformat	libavutilswscale)AVCodecContextAVFormatContextavformatavformat_version)AV_NOPTS_VALUEAV_PIX_FMT_RGBAAV_SAMPLE_FMT_FLTAV_SAMPLE_FMT_FLTPAV_SAMPLE_FMT_S16AV_SAMPLE_FMT_S16PAV_SAMPLE_FMT_S32AV_SAMPLE_FMT_S32PAV_SAMPLE_FMT_U8AV_SAMPLE_FMT_U8PAV_TIME_BASEAV_TIME_BASE_QAVMEDIA_TYPE_AUDIOAVMEDIA_TYPE_VIDEOAVChannelLayoutAVFrame
AVRationalavutil)
swresampleswresample_version)AVStreamc                      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    U/home/agentuser/manim-venv/lib/python3.11/site-packages/pyglet/media/codecs/ffmpeg.py__init__zFileInfo.__init__I   sS    

	



    N)__name__
__module____qualname__rY    rZ   rX   rH   rH   H   s#            rZ   rH   c                  V    e Zd ZU ded<   ded<   ded<   ded<   ded<   ded<   ded<   d	S )
StreamVideoInfointwidthheightsample_aspect_numsample_aspect_denframe_rate_numframe_rate_dencodec_idN)r[   r\   r]   __annotations__r^   rZ   rX   r`   r`   W   s[         JJJKKKMMMMMrZ   r`   c                  <    e Zd ZU ded<   ded<   ded<   dZded<   dS )StreamAudioInfora   sample_formatsample_ratechannelsN
int | Nonesample_bits)r[   r\   r]   ri   rp   r^   rZ   rX   rk   rk   b   sD         MMM"K""""""rZ   rk   c                  *    e Zd Zd ee          fgZdS )
FFmpegFilecontextN)r[   r\   r]   r   r/   _fields_r^   rZ   rX   rr   rr   j   s'        	GGO,,-HHHrZ   rr   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)
r[   r\   r]   r   r   r/   r.   rA   rB   rt   r^   rZ   rX   rv   rv   p   s[        		77?334	''.112	'''""#	j!HHHrZ   rv   c                      e Zd ZdS )FFmpegExceptionNr[   r\   r]   r^   rZ   rX   r}   r}   z           DrZ   r}   c                     | j         t          z   S )zWReturn the audio buffer size

    Buffer size can accommodate 1 sec of audio data.
    )bytes_per_secondr%   )audio_formats    rX   ffmpeg_get_audio_buffer_sizer   ~   s    
 (+GGGrZ   c                     dS )zKInitialize libavformat and register all the muxers, demuxers and protocols.Nr^   r^   rZ   rX   ffmpeg_initr      s      rZ   c                  &    e Zd ZdZdZd
dZddZd	S )MemoryFileObjectz>A class to manage reading and seeking of a ffmpeg file object.i   filer   returnNonec                    | _         d  _        d  _        t           j         dd           rt           j         dd           st	          d           j                             dd            j                                          _         j                             d           d fd}d fd}t          j	        |           _
        t          j        |           _        d S )Nseektellz%File object does not support seeking.r      buffbytesbuf_sizera   r   c                |    j                             |          }t          |          }t          |||           |S N)r   readlenr   )_r   r   data	read_sizerW   s        rX   read_data_cbz/MemoryFileObject.__init__.<locals>.read_data_cb   s9    9>>(++DD		ID$	***rZ   offsetwhencec                l    |t           j        k    rj        S j                            ||          }|S r   )r+   AVSEEK_SIZE	file_sizer   r   )r   r   r   posrW   s       rX   seek_data_cbz/MemoryFileObject.__init__.<locals>.seek_data_cb   s3    000~%)..00CJrZ   )r   r   r   ra   r   ra   )r   ra   r   ra   r   ra   )r   fmt_contextbuffergetattr	Exceptionr   r   r   r+   ffmpeg_read_func	read_funcffmpeg_seek_func	seek_func)rW   r   r   r   s   `   rX   rY   zMemoryFileObject.__init__   s    	ty&$// 	Ewty&RV7W7W 	ECDDD 		q!))	q	 	 	 	 	 		 	 	 	 	 	 %5lCC$5lCCrZ   c                    | j         r+	 t          j        | j                    n# t          $ r Y nw xY w| j        r-	 t          j        | 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   rC   av_freepOSErrorr   rV   s    rX   __del__zMemoryFileObject.__del__   s    ; 	,,,,     	 011111   	 	s   # 
00A 
A$#A$N)r   r   r   r   r   r   )r[   r\   r]   __doc__buffer_sizerY   r   r^   rZ   rX   r   r      sK        HHKD D D D:     rZ   r   filenamer   file_objectr   r   #tuple[FFmpegFile, MemoryFileObject]c           	     l   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          j        t1          |j                  | dd          }|dk    r8t3          d|                     d          z   dz   t7          |          z             t          j        |j        d          }|dk     rt3          d          ||fS )zOpen a media file from a file-like object.

    Returns:
        The structure containing all the information for the media and the memory file object.
    r   r   NKavformat_open_input in ffmpeg_open_filename returned an error opening file utf8 Error code: Could not find stream info)rr   r+   r0   avformat_alloc_contextrs   contentsseekabler   r,   rC   	av_mallocr   r   r   r   r   avio_alloc_contextr   r   r   pbflagsAVFMT_FLAG_CUSTOM_IOavformat_open_inputr
   r}   decodestravformat_find_stream_info)r   r   r   memory_fileav_bufptrresults          rX   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:;;;rZ   c                N   t                      }t          j        t          |j                  | dd          }|dk    r8t          d|                     d          z   dz   t          |          z             t          j        |j        d          }|dk     rt          d          |S )zkOpen the media file.

    Returns:
        The structure containing all the information for the media.
    Nr   r   r   r   r   )	rr   r0   r   r
   rs   r}   r   r   r   )r   r   r   s      rX   ffmpeg_open_filenamer      s     <<D)%*=*=*2*.*.0 0F
 {{k ( 7 78 /025f++> ? ? 	? /dCCFzz:;;;KrZ   r   c                R    t          j        t          | j                             dS )z(Close the media file and free resources.N)r0   avformat_close_inputr
   rs   )r   s    rX   ffmpeg_close_filer      s#    !%"5"566666rZ   c                <   t                      }| j        j        j        |_        | j        j        j        |_        | j        j        j        |_        t          j        | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d          dd          p2t          j        | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d	          dd          }|rt          |j        j                  |_        t          j        | j        j        j	        t          d
          dd          }|rt          |j        j                  |_        t          j        | 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

    Returns:
        The file info instance containing all the meta information.
    rN   Nr   artistalbum_artistrP   rQ   rR   daterT   rU   )rH   rs   r   
nb_streamsrK   rL   rM   rC   av_dict_getmetadatar   r   valuerN   rO   rP   rQ   rR   rS   rT   rU   )r   infoentrys      rX   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
KrZ   stream_indexra   (StreamAudioInfo | StreamVideoInfo | Nonec           	        | j         j        j        |         j        }|j        j        }|j        t
          k    r3t          rt          d|j                   t          d|j                   t          dt          j
        |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                    tB          dk    rt          d|j"                   n*t          d|j#                   t          d|j$                   t          d|j%                   t          d|j&                   t          d|j'                   t          d|j(                   t          d|j)                   t          d |j*                   tW          j,        | j         |d!          }t[          |j        |j        |j        j        |j        j        |j        |j        |j                  }n|j        t\          k    rtB          dk    r|j"        j/        }n|j$        }t          rt          d|j                   t          d|j                   t          dt          j
        |j                                      d                     t          d|j                   t          d	|j                   t          d|j%                   t          d"|           ta          |j        |j%        |          }nd!S |S )#z2Open the stream and retrieve information about it.z codec_type=z
 codec_id=z codec name=z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=Nz channel_count=)1rs   r   streamscodecpar
codec_typer?   _debugprintrh   r*   avcodec_get_namer   	codec_tag	extradataextradata_sizeformatbit_ratebits_per_coded_samplebits_per_raw_sampleprofilelevelrb   rc   sample_aspect_rationumdenfield_ordercolor_rangecolor_primaries	color_trccolor_spacechroma_locationvideo_delayr1   	ch_layoutchannel_layoutrn   rm   block_align
frame_sizeinitial_paddingtrailing_paddingseek_prerollr0   av_guess_frame_rater`   r>   nb_channelsrk   )r   r   	av_streamrs   
frame_rater   channel_counts          rX   ffmpeg_stream_infor  :  s   %-l;DI )G/// !	:.'"4555, 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2%%('*;<<<<('*@AAAlG$4555/7#6777/7#6777.'"4555%w'>???&(@AAA"G$89991$,	4PP
MN'+'+NN
 
 
	1	1	1r!!#-9MM#,M 	4.'"4555, 0111.'":7;K"L"L"S"ST["\"\]]]*gn---, 0111/7#6777#]333N
 
 tKrZ   indexc                   d|cxk    r| j         j        j        k     s$n t          d| j         j        j         d          t	          j        d           }|st          d          t	          j        || j         j        j        |         j        j	                  }|dk     r0t	          j
        t          |                     t          d          |j        j        }t	          j        |          }t          r.t          d|d|j        j                                                   |t$          k    rt	          j        d          }|p|}|t(          k    rt	          j        d	          }|p|}|st          d
|           |j        j        }t          r,t          d|j        j                                                   t	          j        ||d           }|dk     rt          d          t/                      }| j         |_        ||_        |j        j        |_        t9          j                    |_        | j         j        j        |         j        j        |_        |S )Nr   zindex out of range. Only z	 streams.z!Could not allocate Codec Context.z"Could not copy the AVCodecContext.zFound Codec==s
   libvpx-vp9s   libvpxz'No codec found for this media. codecID=zLoaded codec: z(Could not open the media with the codec.) rs   r   r   r}   r*   avcodec_alloc_context3MemoryErroravcodec_parameters_to_contextr   r   avcodec_free_contextr
   rh   avcodec_find_decoderr   r   	long_namer   r$   avcodec_find_decoder_by_namer#   idavcodec_open2rv   rx   ry   r   rw   rC   av_frame_allocrz   r{   )r   r  ry   r   rh   codecnewcodecstreams           rX   ffmpeg_open_streamr    sN   8888-88888e$,:O:Zeeefff2488M ?=>>>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FF!E?""7	BB!E 5 4)14 4 5 5 	5 ~ H C 8 ? ? A ABBB"=%>>FzzHIII^^F LF(F(3FK(**FL|,4U;DNFMrZ   r  r   c                    | j         r&t          j        t          | j                              t	          j        t          | j                             d S r   )rz   rC   av_frame_freer
   r*   r	  ry   )r  s    rX   ffmpeg_close_streamr    sI    | 2U6<00111 v';!<!<=====rZ   	timestampfloatc                $   d}| j         j        j        t          z  }t	          j        | j         dd|||          }|dk     rPt          d          }t          j        ||d           |j	        }t          d|                                z             d S )Nr      zError occurred while seeking. )rs   r   rM   r<   r0   avformat_seek_filer   rC   av_strerrorr   r}   r   )r   r  r   max_tsr   bufdescrs          rX   ffmpeg_seek_filer!    s    E\"+l:F(b!9e F zz"3''63,,,	>#llnn- . . 	.	 zrZ   packet_Pointer[AVPacket]boolc                r    t          j        |           t          j        | j        |          }|dk     rdS dS )zRead from the stream a packet.

    Returns:
        True if the packet was correctly read. False if the end of stream was reached, or an error occurred.
    r   FT)r*   av_packet_unrefr0   av_read_framers   )r   r"  r   s      rX   ffmpeg_readr(    s<     F####DL&99Fzzu4rZ   c                    |j         j        t          k    r|j         j        }nd}t          j        || j        j         j        |j         j                 j         j        t                    }|S Nr   )
r   dtsr2   rC   av_rescale_qrs   r   r   r{   r=   )r   r"  ptsr  s       rX   ffmpeg_get_packet_ptsr.    s`    n,,o!#C$(L$9$A(.(D%FFNy$24 4I rZ   c                d    | j         j        j        }t          j        || j        t                    S r   )rz   r   best_effort_timestamprC   r,  r{   r=   )r  tss     rX   ffmpeg_get_frame_tsr2    s'    			4Br6#3^DDDrZ   c                 N    t          j                    } | st          d          | S )NzCould not allocate AVPacket.)r*   av_packet_allocr  )ps    rX   ffmpeg_init_packetr6    s,    !!A :8999HrZ   c                H    t          j        t          |                      d S r   )r*   av_packet_freer
   r"  s    rX   ffmpeg_free_packetr:    s    5==)))))rZ   c                H    t          j        t          |                      d S r   )r*   r&  r
   r9  s    rX   ffmpeg_unref_packetr<    s    E&MM*****rZ   c                0    t          j        | |           d S r   )r*   av_packet_move_ref)dstsrcs     rX   ffmpeg_transfer_packetrA    s    sC(((((rZ   c                 L    t          j                                                    S )z.Return an informative version string of FFmpeg)rC   av_version_infor   r^   rZ   rX   get_versionrD    s    !##**,,,rZ   c                &    t          |           dz  S Ni@B )r  r  s    rX   timestamp_from_ffmpegrH    s    g%%rZ   c                &    t          | dz            S rF  )ra   rG  s    rX   timestamp_to_ffmpegrJ    s    y7"###rZ   c                  8    e Zd ZU ded<   ded<   ddgZd Zd ZdS )_Packetr'   r"  r  r  c                ~    t                      | _        t          t          | j                  |           || _        d S r   )r'   r"  rA  r
   r  )rW   r"  r  s      rX   rY   z_Packet.__init__  s2    jjuT[116:::"rZ   c                @    t           t          | j                   d S d S r   )r<  r"  rV   s    rX   r   z_Packet.__del__  s&    *,,,,, +*rZ   N)r[   r\   r]   ri   	__slots__rY   r   r^   rZ   rX   rL  rL    sV         ;'I# # #
- - - - -rZ   rL  c                  8     e Zd ZU ded<   ded<   dZ fdZ xZS )VideoPacketra   r  r   r   c                    t                                          ||           d| _        | j        | _        t
          xj        dz  c_        d S )Nr   r   )superrY   r   _next_idr  rQ  )rW   r"  r  	__class__s      rX   rY   zVideoPacket.__init__$  sG    +++
-!rZ   )r[   r\   r]   ri   rT  rY   __classcell__)rU  s   @rX   rQ  rQ    sQ         GGGJJJH" " " " " " " " "rZ   rQ  c                      e Zd ZdS )AudioPacketNr~   r^   rZ   rX   rX  rX  ,  r   rZ   rX  c                     e Zd ZdZdZd@dAdZdBdZedCd            ZdDdZ	dEdZ
dFdZdGdZdDdZdDdZdHd!ZdHd"ZdId$ZdJdKd)ZdLd,ZdMd1ZdNd4ZdOd5ZdPd7ZdQdRd:ZdSd;ZedTd=            Zej        dUd?            ZdS )VFFmpegSource
   d   Nr   r   r   BinaryIO | Nonec                	   d | _         d | _        d | _        d| _        d | _        d | _        |                    t          j                              }|rt          ||          \  | _        | _        nt          |          | _        | j        st          d| d          d | _        d | _        d | _         t          t                                 | _        d | _        t'          | j                  }t)                      | _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        |j        | j        _        t=          |j                  D ]E}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`| j        XtG          | j        |          }ta          d|j1                  }| 2                    |j1                  }	| 2                    |          }
|j3        }|j4        tj          tl          fv rtj          | _7        nd}tp          | _7        ts          |||j:                  | _;        || _        || _        | <                    |
|j:        |	|j4                  | _        | j        s(t{          j>        | j                   t          d	          t{          j?        | j                  }|dk     r)t{          j>        | j                   t          d	|          Gt                      | _         g | _A        t                      | _C        | jD        | _E        | j;        r*t          | j;                  }t          |z              | _H        t                      | _I        | jD        | _J        | K                                | _L        t          |jN                  | _O        | xjO        | jL        z  c_O        d| _P        | Q                                 | jL        dk    r| R                    d
           d S d S )NFzCould not open "")rb   rc   r   r      )rn   sample_sizerm   z$Cannot create sample rate converter.        )S_packet_video_stream_audio_stream_stream_end_file_memory_fileencodesysgetfilesystemencodingr   r   r}   _video_stream_index_audio_stream_index_audio_formatr   r)   img_convert_ctxaudio_convert_ctxr   r   r   rN   rO   rP   rQ   rR   rS   rT   rU   rangerK   r  
isinstancer`   r  r"   rb   rc   video_formatrd   r  re   sample_aspectrf   rg   r   rk   minrn   _get_default_channel_layoutrp   rl   r:   r;   
tgt_formatr6   r   rm   r   get_formatted_swr_contextrD   swr_freeswr_initr6  _eventsr   audioqMAX_QUEUE_SIZE_max_len_audioqr   r   _audio_buffervideoq_max_len_videoq_get_start_timerL   rH  rM   	_duration_fillq_scheduled_fillqr   )rW   r   r   encoded_filename	file_infoir   r  channels_outchannel_inputchannel_outputrp   r   nbytess                 rX   rY   zFFmpegSource.__init__7  s   !! 
 #??3+D+F+FGG 	@,CDTVZ,[,[)DJ))-.>??DJz 	B!"@X"@"@"@AAA#' #' !2wz2244!%$TZ00	LL	#/	$+	'1	%-	#/	"	#/	#/	 y*++ 1	Z 1	ZA%dj!44D$00 .ZT5G5O+DJ::$/*;%( %( %(! )Q..!$"899 23 %3 d122+, !, &,"+,((D/22 Zt7I7Q+DJ::"1dm44 $ @ @ O O!%!A!A,!O!O".%*:<M)NNN&6DOO #%K&7DO$/) + $ 0%2 %2 %2! &,"+,()-)G)GX\Xhjwy}  zL  *M  *M&- R'(>???)*PQQQ#,T-CDDA::'(>???)*PRXYYY)++gg#2 	7243DEEV#*V#3"6"6T*/''#2..00.y/ABB$/) !&
 ?QIIcNNNNN rZ   r  AVChannelLayout | intrm   ra   r  rl   r   int | SwrContextc                (   t           dk     r!t          j        d || j        ||||dd 	  	        S t          j                    }|st          d          t          j        t          |          || j        ||||dd 	  	        dk     rt          d          |S )N   r   zCould not allocate SwrContextz)Could not set sample rate context values.)	rE   rD   swr_alloc_set_optsrw  	swr_allocRuntimeErrorswr_alloc_set_opts2r
   r   )rW   r  rm   r  rl   swr_ctxs         rX   rx  z&FFmpegSource.get_formatted_swr_context  s     !!0*8$/;*7*+T3 3 3
 !*,,G D"#BCCC-eGnn.<do{.;]K./7 7 :;; ;   KLLLNrZ   rn   int | AVChannelLayoutc                    t           dk     rt          j        |           S t                      }t          j        t          |          |            |S )Nr  )rE   rC   av_get_default_channel_layoutr@   av_channel_layout_defaultr
   )rn   layouts     rX   rv  z(FFmpegSource._get_default_channel_layout  sG    !!7AAA$&&F,U6]]HEEEMrZ   r   c                   | j         rt          t          | j                    | j        r4t          -t          j        | j                   t          | j                   | j        r4t          r-t          j	        | j
                   t          | j                   | j        rt          t          | j                   d S d S d S r   )rc  r:  rd  r-   sws_freeContextro  r  re  rD   ry  rp  rg  r   rV   s    rX   r   zFFmpegSource.__del__  s    < 	-.:t|,,, 	4'"5#D$8999 2333 	8 8#D$:;;;#D$6777: 	*+7dj)))))	* 	*77rZ   r  r  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!  rg  rJ  rL   r{  rf  _clear_video_audio_queuesr  r   r   r  r  get_next_video_framers  r|  _get_audio_packet)rW   r  audioq_is_firstcorrect_audio_poscorrect_video_poss        rX   r   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+?+?+?+?&&+?+?&&rZ   rX  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   r  dtrW   s    rX   <lambda>z0FFmpegSource._get_audio_packet.<locals>.<lambda>      $++-- rZ   r   T)r|  popleft_check_low_levelr  pygletclockschedule_once)rW   
audio_datalow_lvls   `  rX   r  zFFmpegSource._get_audio_packet
  sk     [((**
'')) 	)t4 	)L&&'?'?'?'?CCC$(D!rZ   VideoPacket | Nonec                      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    rX   r  z0FFmpegSource._get_video_packet.<locals>.<lambda>%  r  rZ   r   T)r  r  r  r  r  r  r  )rW   video_packetr  s   `  rX   _get_video_packetzFFmpegSource._get_video_packet  sz     { 	4{**,,'')) 	)t4 	)L&&'?'?'?'?CCC$(D!rZ   c                j    | j                                          | j                                         dS )z"Empty both audio and video queues.N)r|  clearr  rV   s    rX   r  z&FFmpegSource._clear_video_audio_queues)  s0    rZ   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)	r  r   r|  r~  r  r  _get_packet_process_packetrf  rV   s    rX   r  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6rZ   r$  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)r   r|  r  r~  r  r  rV   s    rX   r  zFFmpegSource._check_low_level:  ss     t{a3t{#3#3a#7#74;$"6663t{;K;KdNb;b;b4urZ   c                6    t          | j        | j                  S r   )r(  rg  rc  rV   s    rX   r  zFFmpegSource._get_packetJ  s     4:t|444rZ    AudioPacket | VideoPacket | Nonec                   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    r1t#          | j        |          }| j                            |           |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.  rg  rc  rH  rL   r   r   rl  rQ  r   r   r  r  r  appendr   rm  rX  r|  )rW   r  r  audio_packets       rX   r  zFFmpegSource._process_packetO  s     *$*dlCC	))44	T_$	< -1III&t|Y??L g9\_lNd<eefffK|,,, 	 !6!CtG_!_!_&t|Y??LK|,,,trZ   rb  	num_bytescompensation_timeAudioData | Nonec                   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
          r4t          d|j	         d|j                    t          d| j                   |S )NrZ   r   z,Audio queue was starved by the audio driver.zget_audio_data returning ts z with events zremaining events are)r   r|  r  _decode_audio_packetrf  r   r   r   r{  r  popeventsr  )
rW   r  r  r   r  rM   r  r   r  events
             rX   get_audio_datazFFmpegSource.get_audio_datah  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g1EggT^Tegghhh($,777rZ   r  !tuple[bytes | None, float, float]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"  r  r}   r   r   r   rawr  r   r   r2  re  rH  )rW   r  r  size_outr   rM   r  s          rX   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r"  r'   data_outArray[c_uint8]c                V   | j         }|j        t          k    rt          d          t	          j        |j        |          }|dk     rPt          d          }t          j	        ||d           |j
        }t          d|                                           t	          j        |j        |j                  }|dk     rPt          d          }t          j	        ||d           |j
        }t          d|                                           t          d          }	t          dk    r|j        j        j        j        }
n|j        j        j        }
t          j        t+          |	          |
|j        j        j        |j        j        j        d          }|dk     rt          d          t1          | j                  |k     rt          d	          |j        j        j        }|j        j        j        }t          j        | j                  }t;          d
| j        j                  }|||z  z   }|d| j        z
  z  dz  }|d| j        z   z  dz  }t;          tA          ||          |          }tC          |          }||k    r3tE          j#        | j$        ||z
  |          }|dk     rt          d          |j        j        j%        }tM          |tO          tP                              }tE          j)        | j$        |          }tE          j*        | j$        t+          |          |||          }	 ||z  |z  }tM          tW          |j                  |z   tO          tP                              }tE          j*        | j$        t+          |          ||z
  d d          }|dk    rn||z  }y||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   r   z#Error in av_samples_get_buffer_sizez9Output audio buffer is too small for current audio frame!r   r\  zswr_set_compensation failed.),re  rw   r>   r}   r*   avcodec_send_packetry   r   rC   r  r   r   avcodec_receive_framerz   r   r1   r   r   r   rn   av_samples_get_buffer_sizer
   
nb_samples
sample_fmtr   r  rm   av_get_bytes_per_samplerw  ru  r   SAMPLE_CORRECTION_PERCENT_MAXmaxra   rD   swr_set_compensationrp  extended_datar   r   r   swr_get_out_samplesswr_convertr	   )rW   r"  r  r  r  sent_resultr  r   receive_result
plane_sizer  	data_sizer  rm   bytes_per_sampler  wanted_nb_samplesmin_nb_samplesmax_nb_samplesresdata_in
p_data_outout_samplestotal_samples_outr   p_data_offsetsamples_outr  s                               rX   r  z!FFmpegSource._ffmpeg_decode_audio  s   #;,,,!"QRRR1 
 

 ??&s++C{C555IE!"_u||~~"_"_``` 6 L
 

 A&s++C~sC888IE!"UU\\^^"U"UVVV1XX
r!!"09COMM"09BM5*L!, )4 	 q==!"GHHHt!""Y..!"]^^^\*5
*3?!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&"Z/! C Qww%&DEEE,'5(GG$4$455
 4T5KZXX&243I383D3Dk3:JH H	- (,69IIF *-..7   M
 %01G16}1E1E1<?P1PRVXY[ [K a,	-" &47GGrZ   r  rQ  c                   | j         j        }| j         j        }|dz  }t          j        t
          ||d          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   r   RGBAz"Decoding video packet at timestamp)rs  rb   rc   rC   av_image_get_buffer_sizer3   r%   r   _ffmpeg_decode_videor"  r   	ImageDatar2  rd  rH  rL   r  r}   r   r   )
rW   r  rb   rc   pitchr   r   r   
image_datar  s
             rX   _decode_video_packetz!FFmpegSource._decode_video_packet  s    !'")	2?E6STUUXttH$''	A..|/BFKKF NNJ+D,>??I-i88I%.%@L""  	 	 	JJJ	 ( 	^6lF\]]]]]	^ 	^s   B: :C	C	c                T   | j         } t          t                    dz              }t          dz              }|j        t
          k    rt          d          t          j        |j	        |          }|dk     rPt          d          }t          j        ||d           |j        }t          d|                                           t          j        |j	        |j                  }	|	dk     rPt          d          }t          j        |	|d           |j        }t          d|                                           |j        j        j        }
|j        j        j        }t          j        |||t*          |
|d           t-          j        | j        |
||j	        j        j        |
|t*          t4          d d d           | _        t-          j        | j        t9          |j        j        j        t          t          t                                        |j        j        j        d|||           |	S )Nr  z-Trying to decode video on a non-video stream.r   r  z1Video: Error occurred sending packet to decoder. z'Video: Error occurred receiving frame. r   )rd  r   r   r   rw   r?   r}   r*   r  ry   r   rC   r  r   r   r  rz   r   rb   rc   av_image_fill_arraysr3   r-   sws_getCachedContextro  pix_fmtr&   	sws_scaler   r   linesize)rW   r"  r  r  	rgba_ptrsrgba_strider  r  r   r  rb   rc   s               rX   r  z!FFmpegSource._ffmpeg_decode_video)  s   #)WW%%),,	qymm;,,,!"QRRR1 
 

 ??&s++C{C555IE!"fV[VbVbVdVd"f"fggg 6 L
 

 A&s++C~sC888IE!"\ELLNN"\"\]]]%+&-#I{H$3UFA	G 	G 	G  '; 66/8@6?tT4	 1  1 	$.v|49&ww'7'788: : ,/8 #%	' 	' 	' rZ   ro   c                v   | 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 packet timestamp is: )rs  r  r  
IndexErrorr   r  r  
appendleftr  r   r   )rW   r1  r  s      rX   get_next_video_timestampz%FFmpegSource.get_next_video_timestamp[  s      	4; 	)#';#6#6#8#8LL!   E%**--l;;;%1%/BK**<888&&((() B 	;9R99:::	s   / 
<<Tr  c                    | j         sd S 	 |                                 }|sd S |j        dk    r|                     |           |j        |snCt          rt          d|           |j        S )NTr   	Returning)rs  r  r   r  r   r   )rW   r  r  s      rX   r  z!FFmpegSource.get_next_video_framew  s      	4		  1133L t!Q&&)),777!-5E-		  	-+|,,,!!rZ   c                X     d fd}dd}t           | |                                S )Nr   Iterator[AVStream]c               3     K   j         j        } j        j        fD ] }|| j        j        |         j        }|V  !d S r   )rg  rs   rl  rm  r   r   )rx   idxr  rW   s      rX   r   z-FFmpegSource._get_start_time.<locals>.streams  s[      !Z/N0$2JK  ;'08=F	 rZ   Iterator[int]c              3     K   dV  | D ]K}|j         }|t          k    rdV  t          j        ||j        t
                    }t          |          }|V  Ld S r*  )rL   r2   rC   r,  r{   r=   rH  )r   r  startrL   s       rX   start_timesz1FFmpegSource._get_start_time.<locals>.start_times  s      GGG! ! !)N**GGG#0171A1?A A
 3:>>
     ! !rZ   )r   r  )r   r
  )r  )rW   r   r  s   `  rX   r  zFFmpegSource._get_start_time  sU    	 	 	 	 	 	
	! 
	! 
	! 
	! ;;wwyy))***rZ   r   c                    | j         S r   )rn  rV   s    rX   r   zFFmpegSource.audio_format  s    !!rZ   r   c                N    || _         || j                                         d S d S r   )rn  r|  r  )rW   r   s     rX   r   zFFmpegSource.audio_format  s0    "=K =rZ   r   )r   r   r   r]  )
r  r  rm   ra   r  r  rl   ra   r   r  )rn   ra   r   r  r   )r  r  r   r   )r   rX  )r   r  )r   r$  )r   r  )rb  )r  ra   r  r  r   r  )r  rX  r  r  r   r  )r"  r'   r  r  r  r  r   ra   )r  rQ  r   r   )r"  r'   r  r  r   ra   )r   ro   T)r  r$  r   ro   )r   ra   )r   r   )r   r   r   r   )r[   r\   r]   r  r}  rY   rx  staticmethodrv  r   r   r  r  r  r  r  r  r  r  r  r  r  r  r  r  r  propertyr   setterr^   rZ   rX   rZ  rZ  0  s#       $&! Ns s s s sj   (    \* * * *2 2 2 2h          

 
 
 
    5 5 5 5
   2$ $ $ $ $L   0^ ^ ^ ^@^ ^ ^ ^F0 0 0 0d   8" " " " "(+ + + +. " " " X"            rZ   rZ  debug_mediaTF   c                       e Zd ZddZdddZdS )FFmpegDecoderr   Sequence[str]c                    dS )N)z.mp3z.oggr^   rV   s    rX   get_file_extensionsz!FFmpegDecoder.get_file_extensions  s    ~rZ   Tr   r   r   r]  	streamingr$  FFmpegSource | StaticSourcec                `    |rt          ||          S t          t          ||                    S r   )rZ  r    )rW   r   r   r  s       rX   r   zFFmpegDecoder.decode  s2     	>$///Xt < <===rZ   N)r   r  r  )r   r   r   r]  r  r$  r   r  )r[   r\   r]   r  r   r^   rZ   rX   r  r    sA           > > > > > > >rZ   r  list[FFmpegDecoder]c                      t                      gS r   )r  r^   rZ   rX   get_decodersr     s    OOrZ   listc                     g S r   r^   r^   rZ   rX   get_encodersr#    s    IrZ   )r   r   r   r   r   r   )r   r   r   rr   )r   rr   )r   rr   r   rH   )r   rr   r   ra   r   r   )r   rr   r  ra   r   rv   )r  rv   r   r   )r   rr   r  r  r   r   )r   rr   r"  r#  r   r$  )r   rr   r"  r#  r   r  )r  rv   r   r  )r   r#  )r   r  )r   r!  )yr   
__future__r   rj  collectionsr   ctypesr   r   r   r   r	   r
   r   r   r   r   r   r   r   dataclassesr   typingr   r   r   r   r  
pyglet.libr   pyglet.media.exceptionsr   pyglet.utilr   r   rJ   r   baser   r   r   r    r!   r"   
ffmpeg_libr#   r$   r%   r&   r'   r(   r)   r*   r+   r,   r-   ffmpeg_lib.libavformatr.   r/   r0   r1   ffmpeg_lib.libavutilr2   r3   r4   r5   r6   r7   r8   r9   r:   r;   r<   r=   r>   r?   r@   rA   rB   rC   ffmpeg_lib.libswresamplerD   rE   rF   rH   r`   rk   rr   rv   r}   r   r   r   r   r   r   r   r  r  r  r!  r(  r.  r2  r6  r:  r<  rA  rD  rH  rJ  rL  rQ  rX  rZ  optionsr   av_log_set_levelr  r   r#  r^   rZ   rX   <module>r3     s7   1 1 " " " " " " 



                                    " ! ! ! ! ! > > > > > > > > > > > >            8 8 8 8 8 8 & & & & & & & &       ` ` ` ` ` ` ` ` ` ` ` ` ` ` ` `                          ` _ _ _ _ _ _ _ _ _ _ _                                       ( E D D D D D D D 1000000                # # # # # # # #           9   	 	 	 	 	* 	 	 	H H HV V V- - - - - - - -`* * * *Z   07 7 7 7
3 3 3 3lL L L L^. . . .b> > > >. . . .   
 
 
 
E E E E
   * * *+ + +) ) )- - -
& & &$ $ $- - - - - - - - 
" 
" 
" 
" 
"' 
" 
" 
"	 	 	 	 	' 	 	 	z	  z	  z	  z	  z	 ? z	  z	  z	 z 	>-  FFFFA	> 	> 	> 	> 	>L 	> 	> 	>        rZ   