o
    2jX                     @   s   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 d dlmZ d dlmZ d d	lmZmZ d d
lmZmZ ejdefddZejejG dd deZdS )    N)libav)Codec)CodecContextwrap_codec_context)StreamContainer)
Dictionary)	err_check)Packet)Streamwrap_stream)dict_to_avdictto_avrationalselfc                 C   s   t  | _| jd@ dkrk| jd ur!t| jjddr!|  jdO  _d S z*| t| j W | jd u rC| jj	j
tj@ sCtt| jj |  jdO  _d S | jd u rc| jj	j
tj@ sctt| jj |  jdO  _w d S )N      closedF   )r   streams_myflagfilegetattrr   libav_write_trailerptroformatflagsAVFMT_NOFILEavio_closepcythonaddresspbr    r"   N/var/www/html/whisper/venv/lib/python3.10/site-packages/av/container/output.pyclose_output   s   r$   c                   @   s   e Zd Zdd Zdd Zdd Zd-dedB fd	d
Zd.dede	fddZ
	d.de	dedB fddZde	de	fddZdededefddZd-dedB fddZejdd Zedd Zed d! Zed"d# Zed$d% Zd&d' Zd(d) Zd*efd+d,ZdS )/OutputContainerc                 O   sD   t  | _i | _tj t | _W d    d S 1 sw   Y  d S N)r   r   metadatar   nogilr   av_packet_alloc
packet_ptr)r   argskwargsr"   r"   r#   	__cinit__&   s
   "zOutputContainer.__cinit__c                 C      t |  d S r&   r$   r!   r"   r"   r#   __del__,      zOutputContainer.__del__c                 C   s>   t j tt | j W d    d S 1 sw   Y  d S r&   )r   r(   r   av_packet_freer   r*   r!   r"   r"   r#   __dealloc__/   s   "zOutputContainer.__dealloc__Noptionsc              	   K   sn  t |d}|j}t| jj|jtjs t| jj	d|j	dt
| j|}t|}|jtjkr~tj|_|dd|_|dd|_|dd	|_|d
d|_zt|dt|j W n	 tyi   Y nw t|pndt|j |j|_|j|_nr|jtjkrtj}	ttj|tjd	t|	tj |	rt tj!tj" |	d	 |_#|dd	|_|d
d|_zt|dt|j W n	 ty   Y nw |du rd|_$nt|t%u r||_$nt&d|j|_t't|j(d | jjj)tj*@ r| j)tj+O  _)t,t-|j.| t/||d}
t0| ||
}| j12| |r%|j34| |5 D ]\}}t6||| q)|S )a  add_stream(codec_name, rate=None)

        Creates a new stream from a codec name and returns it.
        Supports video, audio, and subtitle streams.

        :param codec_name: The name of a codec.
        :type codec_name: str
        :param dict options: Stream options.
        :param \**kwargs: Set attributes for the stream.
        :rtype: The new :class:`~av.stream.Stream`.

        w format does not support  codecwidthi  heighti  bit_rater   bit_rate_tolerancei  	time_base   i }  Ni  'audio stream `rate` must be: int | None   )7r   r   r   avformat_query_codecr   idFF_COMPLIANCE_NORMAL
ValueErrorformatnameavformat_new_streamavcodec_alloc_context3typeAVMEDIA_TYPE_VIDEOAV_PIX_FMT_YUV420Ppix_fmtpopr8   r9   r:   r;   r   r   r   r<   KeyError	framerateavg_frame_rateAVMEDIA_TYPE_AUDIONULLavcodec_get_supported_configAV_CODEC_CONFIG_SAMPLE_FORMATcastpointerAVSampleFormat
sample_fmtsample_rateint	TypeErrorav_channel_layout_default	ch_layoutr   AVFMT_GLOBALHEADERAV_CODEC_FLAG_GLOBAL_HEADERr   avcodec_parameters_from_contextcodecparr   r   r   
add_streamr4   updateitemssetattr)r   
codec_namerater4   r,   	codec_objcodecstreamctxoutpy_codec_context	py_streamkvr"   r"   r#   ra   3   sz   


zOutputContainer.add_streamre   returnc                 K   s  |  }t|}tj}|tjkrt|}|tjkr,t|}|tjkr,td||tjkr8|j}|j	}n|j}|j	}t
| jj|tjsTt| jjd|dt| jtj}	|	tjkretd||	j_||	j_|tjkr|dd|	j_|dd|	j_|durt|t|	j n|tjkr|durt	|tu r||	j_ntd	t | |	d}
| j!"|
 |# D ]
\}}t$|
|| q|
S )
a  add_mux_stream(codec_name, rate=None)

        Creates a new stream for muxing pre-encoded data without creating a
        :class:`.CodecContext`. Use this when you want to mux packets that were
        already encoded externally and no encoding/decoding is needed.

        :param codec_name: The name of a codec.
        :type codec_name: str
        :param \**kwargs: Set attributes for the stream (e.g. ``width``, ``height``,
            ``time_base``).
        :rtype: The new :class:`~av.stream.Stream`.

        zUnknown codec: r6   r7   Could not allocate streamr8   r   r9   Nr>   )%encoder   avcodec_find_encoder_by_namer   rQ   avcodec_find_decoder_by_nameavcodec_descriptor_get_by_namerC   rA   rH   r@   r   r   rB   rD   rE   rF   MemoryErrorr`   codec_id
codec_typerI   rL   r8   r9   r   r   rO   rP   rY   rX   rZ   r   r   ra   rc   rd   )r   re   rf   r,   codec_name_bytesrh   codec_descriptorrw   rx   ri   rm   rn   ro   r"   r"   r#   add_mux_stream   sZ   









zOutputContainer.add_mux_streamtemplateopaquec                 K   s\  |du r	|j dk}|jdu r| j|fi |S |r|jj}nt|jjjd}|j}t| jj	|j
tjsAt| jjd|jdt| j|}t|}tt||jj d|_|jj|_|jj|_| jj	jtj@ rt| jtjO  _|s{|jj|_tt|j| t||d}| jdO  _t| ||}	| j|	 | D ]
\}
}t|	|
| q|	S )a  
        Creates a new stream from a template. Supports video, audio, subtitle, data and attachment streams.

        :param template: Copy codec from another :class:`~av.stream.Stream` instance.
        :param opaque: If True, copy opaque data from the template's codec context.
        :param \**kwargs: Set attributes for the stream.
        :rtype: The new :class:`~av.stream.Stream`.
        Nvideor5   r6   r7   r      ) rH   codec_context'_add_stream_without_codec_from_templaterh   r   rE   r   r   r@   r   rA   rB   rC   rD   rF   rG   r   avcodec_parameters_to_contextr`   	codec_tagr<   r   r]   r^   r_   r   	_ctxflagsr   r   ra   rc   rd   )r   r|   r}   r,   rg   rh   ri   rj   rl   rm   rn   ro   r"   r"   r#   add_stream_from_template   s@   






z(OutputContainer.add_stream_from_templatec                 K   s   |j jj}|tjtjhvrtd|j dt| j t	j
}|t	j
kr'tdtt|j|j j |j j|_|j j|_|j j|_|j j|_t| |d }| j| t|j|_| D ]
\}}t||| q\|S )Nztemplate stream of type z has no codec contextrq   )r   r`   rx   r   AVMEDIA_TYPE_ATTACHMENTAVMEDIA_TYPE_DATArC   rH   rF   r   rQ   rv   r   avcodec_parameters_copyr<   
start_timedurationdispositionr   r   ra   dictr'   rc   rd   )r   r|   r,   rx   ri   rm   rn   ro   r"   r"   r#   r   &  s*   





z7OutputContainer._add_stream_without_codec_from_templaterE   mimetypedatac                 C   s  t | jtj}|tjkrtdt j|j_t j	|j_
t|}|rTttjt |d }|tjkr6tdt|D ]}|| ||< q:d||< ttj||j_||j_t|j}tt |d| d | }	tt |d|	d t| |d}
| j|
 |
S )a  
        Create an attachment stream and embed its payload into the container header.

        - Only supported by formats that support attachments (e.g. Matroska).
        - No per-packet muxing is required; attachments are written at header time.
        rq   r   z"Could not allocate attachment datar   s   filenames   mimetypeN)r   rF   r   r   rQ   rv   r   r`   rx   AV_CODEC_ID_NONErw   lenrT   p_uchar	av_mallocrange	extradataextradata_sizer   r'   r   av_dict_setrr   r   r   ra   )r   rE   r   r   ri   payload_sizebufimeta_ptr
mime_bytesrm   r"   r"   r#   add_attachmentG  s0   



zOutputContainer.add_attachmentc                 C   s  t j}t j}|durT| }t|}|t jkrt|}|t jkr3t|}|t jkr3td| |t jkr;|jn|j}t	| j
j|tjsTt| jjd|dt| j
|}|t jkrdtdt j}|t jkrt|}|t jkrztd| j
jjtj@ r| jtjO  _tt|j| ntj|j_|t jkr|j|j_d}	|t jkrt||d}	t| ||	}
| j|
 |r|
j | |
S )a4  add_data_stream(codec_name=None)

        Creates a new data stream and returns it.

        :param codec_name: Optional name of the data codec (e.g. 'klv')
        :type codec_name: str | None
        :param dict options: Stream options.
        :rtype: The new :class:`~av.data.stream.DataStream`.
        NzUnknown data codec: r6   r7   rq   z Could not allocate codec context)!r   rQ   rr   r   rs   rt   ru   rC   rA   r@   r   r   rB   rD   rE   rF   rv   rG   r   r]   r^   r   r_   r`   r   rx   rw   r   r   r   ra   r4   rb   )r   re   r4   rh   rz   ry   rw   ri   rj   rl   rm   r"   r"   r#   add_data_streamo  sR   














zOutputContainer.add_data_streamc                    s  | j d@ rdS t  | jD ]:}|j}|durC|jsC| j D ]\}}|j|| q|jd@ sC|	  | jD ]}||jvrB 
| q6|  qt| jdu rR| jnd}|}| jjtjkru| jjjtj@ suttt| jj|tj tt| jj| j| j| jd t | j| j!}|" }| t#| jt|j |D ]}||vr 
| q fdd| j D }	|	rddl$}
|
%t&}|'d	|	  |  j dO  _ dS )
z,Write the file header! Called automatically.r   Nr    )encodingerrorsc                    s   i | ]\}}| vr||qS r"   r"   ).0rn   ro   used_optionsr"   r#   
<dictcomp>  s    z2OutputContainer.start_encoding.<locals>.<dictcomp>r   zSome options were not used: %s)(r   setr   r   is_openr4   rc   
setdefaultr   openadd_finalize_for_outputosfsencoder   rE   r   r    r   rQ   r   r   r   r   r   	avio_openr   AVIO_FLAG_WRITEr   r'   metadata_encodingmetadata_errorsr   container_optionscopyavformat_write_headerlogging	getLogger__name__warning)r   ri   rj   rn   ro   name_objrE   all_optionsr4   unused_optionsr   logr"   r   r#   start_encoding  sT   









zOutputContainer.start_encodingc                 C   s\   t  }tj}tj}	 tt|}|tjkr	 |S t| jj|j	tj
dkr-||j q
)zC
        Returns a set of all codecs this format supports.
        Tr   )r   r   rQ   r   av_codec_iterater   r@   r   r   rA   rB   r   rE   )r   resultrh   r}   r"   r"   r#   supported_codecs  s   

z OutputContainer.supported_codecsc                 C      t | jjjS )zL
        Returns the default video codec this container recommends.
        )r   avcodec_get_namerD   optrvideo_codecr!   r"   r"   r#   default_video_codec     z#OutputContainer.default_video_codecc                 C   r   )zL
        Returns the default audio codec this container recommends.
        )r   r   rD   r   audio_codecr!   r"   r"   r#   default_audio_codec  r   z#OutputContainer.default_audio_codecc                 C   r   )zO
        Returns the default subtitle codec this container recommends.
        )r   r   rD   r   subtitle_codecr!   r"   r"   r#   default_subtitle_codec  r   z&OutputContainer.default_subtitle_codecc                 C   r.   r&   r/   r!   r"   r"   r#   close$  r1   zOutputContainer.closec                 C   s0   t |tr| | d S |D ]}| | qd S r&   )
isinstancer	   mux_one)r   packetspacketr"   r"   r#   mux'  s
   
zOutputContainer.muxr   c                 C   s   |    |jjdk sttj|jj| jjkrtd| jj|jj }|	|j
 | t| j|j tj t| j| j}W d    n1 sJw   Y  | | d S )Nr   zBad Packet stream_index.)r   r   stream_indexr   rT   uint
nb_streamsrC   r   _rebase_timer<   r   r   av_packet_refr*   r(   av_interleaved_write_frame)r   r   ri   retr"   r"   r#   r   0  s   zOutputContainer.mux_one)NNr&   )r   
__module____qualname__r-   r0   r3   r   ra   strr
   r{   boolr   r   bytesr   r   r   ccallr   propertyr   r   r   r   r   r   r	   r   r"   r"   r"   r#   r%   #   s@    aN
E
!(G
@



	r%   )r   r   cython.cimportsr   r   cython.cimports.av.codec.codecr    cython.cimports.av.codec.contextr   r   $cython.cimports.av.container.streamsr   cython.cimports.av.dictionaryr   cython.cimports.av.errorr   cython.cimports.av.packetr	   cython.cimports.av.streamr
   r   cython.cimports.av.utilsr   r   cfuncr%   r$   finalcclass	Containerr"   r"   r"   r#   <module>   s     