
    CcO                         d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZ ddlmZ ddlmZ  G d	 d
e      Z G d de      Z G d de	      Zy)a:  Read and write Ogg bitstreams and pages.

This module reads and writes a subset of the Ogg bitstream format
version 0. It does *not* read or write Ogg Vorbis files! For that,
you should use mutagen.oggvorbis.

This implementation is based on the RFC 3533 standard found at
http://www.xiph.org/ogg/doc/rfc3533.txt.
    N)BytesIO)Type)FileType)cdataresize_bytesMutagenErrorloadfileseek_endbchrreraise)
StreamInfo)Tagsc                       e Zd ZdZy)errorzOgg stream parsing errors.N)__name__
__module____qualname____doc__     -/usr/lib/python3/dist-packages/mutagen/ogg.pyr   r      s    $r   r   c                   ,   e Zd ZdZdZdZdZdZdZdZ	dZ
ddZd Zej                  Zd Zd Zed	        Zd
 Z ed d d      Z ed d d      Z ed d d      Zed        Zedd       Zed        Ze	 	 dd       Zed        Zedd       Zy)OggPageav  A single Ogg page (not necessarily a single encoded packet).

    A page is a header of 26 bytes, followed by the length of the
    data, followed by the data.

    The constructor is given a file-like object pointing to the start
    of an Ogg page. After the constructor is finished it is pointing
    to the start of the next page.

    Attributes:
        version (`int`): stream structure version (currently always 0)
        position (`int`): absolute stream position (default -1)
        serial (`int`): logical stream serial number (default 0)
        sequence (`int`): page sequence number within logical stream
            (default 0)
        offset (`int` or `None`): offset this page was read from (default None)
        complete (`bool`): if the last packet on this page is complete
            (default True)
        packets (list[bytes]): list of raw packet data (default [])

    Note that if 'complete' is false, the next page's 'continued'
    property must be true (so set both when constructing pages).

    If a file-like object is supplied to the constructor, the above
    attributes will be filled in based on it.
    r   NTc                    g | _         |y|j                         | _        |j                  d      }t	        |      dk(  rt
        	 t        j                  d|      \  }| _        | _	        | _
        | _        | _        }}|dk7  r"t        d|d|j                         dz
  fz        | j                  dk7  rt        d| j                  z        d}g }|j                  |      }t	        |      |k7  rt        d	|z        t        |      D ]   }	||	z  }|	d
k  s|j                  |       d}" |r|j                  |       d| _        |D 
cg c]  }
|j                  |
       c}
| _         | j                   D cg c]  }t	        |       c}|k7  rt        d      y# t        j                  $ r t        d|z        w xY wc c}
w c c}w )zRaises error, IOError, EOFErrorN   r   z
<4sBBqIIiBz"unable to read full header; got %r   OggSzread %r, expected %r, at 0x%xzversion %r unsupportedzunable to read %r lacing bytes   Fzunable to read full data)packetstelloffsetreadlenEOFErrorstructunpackversion_OggPage__type_flagspositionserialsequencer   	bytearrayappendcomplete)selffileobjheaderoggscrcsegmentstotallacingslacing_bytesclps               r   __init__zOggPage.__init__I   s    ?llnb!v;!N	G %mmL&AT4<!2]DK( 7?7gw||~2;4 4 5 5 <<104<<?@@||H-|(88CDD<( 	AQJE3wu%		
 NN5!!DM189AQ9 LL)qCF)W4233 53 || 	G<vEFF	G0 :)s   8F 	G 7G"F=c                 d    	 | j                         |j                         k(  S # t        $ r Y yw xY w)z7Two Ogg pages are the same if they write the same data.F)writeAttributeError)r.   others     r   __eq__zOggPage.__eq__w   s0    	JJLEKKM12 		s    # 	//c           	         g d}|D cg c]  }|dt        | |       }}dt        |       j                  dj                  |      t	        t        t        | j                              t        | j                        fz  S c c}w )N)	r&   r(   r)   r*   r    r-   	continuedfirstlast=z<%s %s, %d bytes in %d packets> )getattrtyper   joinsummapr"   r   )r.   attrsattrvaluess       r   __repr__zOggPage.__repr__   sv    ;DIJDT74#67JJ0J&!13s37M3N4  	 Ks   Bc           
      N   t        j                  dd| j                  | j                  | j                  | j
                  | j                  d      g}g }| j                  D ]:  }t        t        |      d      \  }}|j                  d|z  t        |      z          < dj                  |      }| j                  s|j                  d      r|dd	 }|j                  t        t        |                   |j                  |       |j                  | j                         dj                  |      }t!        j"                  |j%                  t&        j(                        d	       d
z  }t'        j*                  |      j%                  t&        j(                        }|dd |z   |dd z   }|S )zReturn a string encoding of the page header and data.

        A ValueError is raised if the data is too big to fit in a
        single page.
        z	<4sBBqIIir   r   r      r       Nl          )r$   packr&   r'   r(   r)   r*   r   divmodr"   r,   r   rH   r-   endswithextendzlibcrc32	translater   bitswap
to_uint_be)r.   datalacing_datadatumquotremr2   s          r   r<   zOggPage.write   s^    KKWdllD<M<Mt{{DMM1F

 \\ 	;Es5z3/ID#w~S	9:	; hh{+}}!5!5g!>%cr*KD[)*+K DLL!xx~ 

4>>%--8"==K s#--emm<CRy3bc*r   c                     d}| j                   D ]"  }t        t        |      d      \  }}||dz   z  }$ | j                  s
dk(  r|dz  }|t	        t        t        | j                               z  }|S )zTotal frame size.r   r      r   )r   rV   r"   r-   rI   rJ   )r.   sizer`   ra   rb   s        r   re   zOggPage.size   sw     \\ 	Es5z3/ID#D1HD	 }} AIDCT\\*++r   c                 j    d|z  }|r| xj                   |z  c_         y | xj                   | z  c_         y Nrd   )r'   )r.   bitvalmasks       r   
__set_flagzOggPage.__set_flag   s2    Cx%$&r   c                 B    t        j                  | j                  d      S Nr   r   test_bitr'   r.   s    r   <lambda>zOggPage.<lambda>       U^^D$5$5q9 r   c                 &    | j                  d|      S rm   _OggPage__set_flagr.   vs     r   rq   zOggPage.<lambda>       1- r   z5The first packet is continued from the previous page.)docc                 B    t        j                  | j                  d      S rg   rn   rp   s    r   rq   zOggPage.<lambda>   rr   r   c                 &    | j                  d|      S rg   rt   rv   s     r   rq   zOggPage.<lambda>   rx   r   z.This is the first page of a logical bitstream.c                 B    t        j                  | j                  d      S N   rn   rp   s    r   rq   zOggPage.<lambda>   rr   r   c                 &    | j                  d|      S r}   rt   rv   s     r   rq   zOggPage.<lambda>   rx   r   z-This is the last page of a logical bitstream.c                 B   |}	 	 t        |       }|j                  |k7  r| j                  |j                   d       ||_        | j                  |j                                | j                  |j                  |j                  z   d       |dz  }# t        $ r Y yw xY w)a*  Renumber pages belonging to a specified logical stream.

        fileobj must be opened with mode r+b or w+b.

        Starting at page number 'start', renumber all pages belonging
        to logical stream 'serial'. Other pages will be ignored.

        fileobj must point to the start of a valid Ogg page; any
        occurring after it and part of the specified logical stream
        will be numbered. No adjustment will be made to the data in
        the pages nor the granule position; only the page number, and
        so also the CRC.

        If an error occurs (e.g. non-Ogg data is found), fileobj will
        be left pointing to the place in the stream the error occurred,
        but the invalid data will be left intact (since this function
        does not change the total file size).
        rd   r   N)r   r)   seekre   r#   r*   r<   r    )r/   r)   startnumberpages        r   renumberzOggPage.renumber   s    * 
,w' ;;&( diiZ+"DMMM$**,'LLtyy0!4aKF   s   B 	BBc                    | d   j                   }| d   j                  }g }|r4| d   j                  rt        d      | d   j                  s.t        d      | r!| d   j                  r|j                  dg       | D ]  }||j                   k7  rt        d|z        ||j                  k7  rt        d|z        |dz  }|j                  sO|j                  r"|d   j                  |j                  d          n|j                  |j                  d   g       |j                  d	 |j                  dd
 D                |D cg c]  }dj                  |       c}S c c}w )zConstruct a list of packet data from a list of Ogg pages.

        If strict is true, the first page must start a new packet,
        and the last page must end the last packet.
        r   zfirst packet is continuedrR   zlast packet does not completer   zinvalid serial number in %rzbad sequence number in %rrd   c              3   "   K   | ]  }|g 	 y wNr   ).0r9   s     r   	<genexpr>z%OggPage.to_packets.<locals>.<genexpr>  s     =qs=s   N)	r)   r*   rA   
ValueErrorr-   r,   r   rX   rH   )pagesstrictr)   r*   r   r   r9   s          r   
to_packetszOggPage.to_packets   sC    q8$$Qx!! !<==9%% !@AAuQx))NNC5! 	>D$ !>!EFFT]]* !<t!CDDA||>>BK&&t||A7NNDLLO#45=DLL,<==	> &-----s   Ec                 j   | j                  |      }|D cg c]  }t        |       c}|D cg c]  }t        |       c}k7  r| j                  ||d   j                        S dj	                  |      }g }|D ]  }t               }|j                  |_        |j                  |_        |j                  |_        |j                  |_        |j                  D ]9  }|dt        |       |t        |      d }}	|j                  j                  |	       ; |j                  |        |rJ |S c c}w c c}w )aL  Like from_packets but in case the size and number of the packets
        is the same as in the given pages the layout of the pages will
        be copied (the page size and number will match).

        If the packets don't match this behaves like::

            OggPage.from_packets(packets, sequence=old_pages[0].sequence)
        r   r   N)r   r"   from_packetsr*   rH   r   r-   rA   r(   r   r,   )
clsr   	old_pagesold_packetsr9   new_data	new_pagesoldnewr^   s
             r   _from_packets_try_preservez"OggPage._from_packets_try_preserve  s    nnY/#$qCF$(EAQ(EE##GYq\-B-BCC88G$	 		"C)C<<CL<<CLMMCM<<CL[[ )!)'3q6!2HSVW4Eh""4() S!		" |% %(Es
   D+D0c                    |dz  dz  }g }t               }||_        | D ]H  }|j                  j                  d       |s"|d| ||d }}|j                  |k  r0t        |j                        dk  r|j                  dxx   |z  cc<   n|j                  d   r'd|_        t        |j                        dk(  r#d|_        n|j                  j                  d       |j                  |       t               }|d   j                   |_	        |d   j                  dz   |_        |j                  j                  |       t        |      |k  r|j                  dxx   |z  cc<   d}|r'K |j                  r|j                  |       |S )a%  Construct a list of Ogg pages from a list of packet data.

        The algorithm will generate pages of approximately
        default_size in size (rounded down to the nearest multiple of
        255). However, it will also allow pages to increase to
        approximately default_size + wiggle_room if allowing the
        wiggle room would finish a packet (only one packet will be
        finished in this way per page; if the next packet would fit
        into the wiggle room, it still starts on a new page).

        This method reduces packet fragmentation when packet sizes are
        slightly larger than the default page size, while still
        ensuring most pages are of the average size.

        Pages are numbered started at 'sequence'; other information is
        uninitialized.
        r   r   NrR   Frd   )
r   r*   r   r,   re   r"   r-   r(   poprA   )	r   r*   default_sizewiggle_room
chunk_sizer   r   packetr^   s	            r   r   zOggPage.from_packets;  sc   * #c)S0
y  	!FLL$%kz2F:;4Gf99|+DLL0AC0GLL$,$ ||B'(-t||,1,.DM((,LL&"9D).r););%;DN$)"I$6$6$:DMLL''-v;,LL$.$ F1 	!8 <<LLr   c           
      P   t        |      rt        |      st        d      |d   j                  }t        |t	        ||t        |      z               D ]   \  }}||_        |d   j
                  |_        " |d   j                  |d   _        |d   j                  |d   _        |d   j                  |d   _        |d   j                  |d   _        |d   j                  |d   _        |d   j                  |d   _	        |d   j                  s%t        |d   j                        dk(  r
d|d   _        |D cg c]  }| j                  |       }}t        |      t        |      z
  }	|	dkD  r|j                  dg|	z         n#|	dk  rdj                  ||	dz
  d       g||	dz
  d d}
d}t        |      t        |      k(  sJ t        ||      D ]q  \  }}|j                  |
z   }t        |      }t!        ||j"                  ||       |j%                  |d       |j                  |       ||z   }|
||j"                  z
  z  }
s t        |      t        |      k7  rG|j%                  |d       |d   j
                  }|d   j                  dz   }| j'                  |||       yyc c}w )a  Replace old_pages with new_pages within fileobj.

        old_pages must have come from reading fileobj originally.
        new_pages are assumed to have the 'same' data as old_pages,
        and so the serial and sequence numbers will be copied, as will
        the flags for the first and last pages.

        fileobj will be resized and pages renumbered as necessary. As
        such, it must be opened r+b or w+b.
        zempty pages list not allowedr   rR   rd   r   N)r"   r   r*   zipranger)   rB   rC   rA   r-   r   r(   r<   rX   rH   r    r   re   r   r   )r   r/   r   r   rB   r   seqr9   r   
pages_diffoffset_adjustnew_data_endold_pager^   r    	data_sizer)   r*   s                     r   replacezOggPage.replacex  s    9~S^;<< !%%Y"5%#i.*@AC 	.ID#DM#A,--DK	.
 'q\//	!%aL--	!!*1!7!7	!'m11	"&r]//	"!*2!7!7	"}%%#im.C.C*D*I%'IbM"*34QCIIaL44 ^c(m3
>OOSEJ./!^),(:>?2K)L(MHZ!^_% 9~X...!)X6 	9NHd__}4FD	I(--FCLL#MM$!I-Li(--78M	9 y>S^+LLq)r]))F }--1HLL&(3	 ,3 5s   8J#c                 $   t        | d       | j                         }	 |j                  d      }t        ||d       }fd}d}	 t        |      }|j                  |k(  r ||      r|j                  r|S |}nd}	 | j                  d       	 t        |       }	 |j                  |k(  r ||      r|}|j                  r	 |S t        |       }4# t        $ r t	        d      w xY w# t        $ r Y uw xY w# t        $ r |cY S t        $ r |cY S w xY w)aw  Find the last page of the stream 'serial'.

        If the file is not multiplexed this function is fast. If it is,
        it must read the whole the stream.

        This finds the last page in the actual file object, or the last
        page in the stream (with eos set), whichever comes first.

        If finishing is True it returns the last page which contains a packet
        finishing on it. If there exist pages but none with finishing packets
        returns None.

        Returns None in case no page with the serial exists.
        Raises error in case this isn't a valid ogg stream.
        Raises IOError.
        i   r   zunable to find final Ogg headerNc                 ,     xs | j                   dk7  S )NrR   )r(   )r   	finishings    r   is_validz#OggPage.find_last.<locals>.is_valid  s     =7DMMR$77r   r   )r
   r!   rindexr   r   r   r   r)   rC   r   r#   )	r/   r)   r   r^   indexbytesobjr   	best_pager   s	     `      r   	find_lastzOggPage.find_last  s0   ( 	)$||~	;KK(E 4<(	8 		!8$D {{f$$99K $I 	 	Q	7#D;;&(~$(	yy w' 3  	;9::	;  		.  	 		s;   C C& 3C5 C5 C#&	C21C25D
DDr   )F)r   i   i   )r   r   r   r   r&   r'   r(   r)   r*   r    r-   r:   r?   object__hash__rN   r<   propertyre   ru   rA   rB   rC   staticmethodr   r   classmethodr   r   r   r   r   r   r   r   r   %   s)   6 GLHFHFH,4\ HB  ' 9-CEI
 9-<>E
 9-;=D
 $ $L ". ".H  @ 7;!%: :x =4 =4~ < <r   r   c                       e Zd ZU dZee   ed<   ee   ed<   ee   ed<   ddgZ	 e
       d        Z e
d	      dd       Zd Z e
d	      dd       Zy
)OggFileTypezcOggFileType(filething)

    An generic Ogg file.

    Arguments:
        filething (filething)
    _Info_Tags_Errorzapplication/oggzapplication/x-oggc                    |j                   }	 | j                  |      | _        | j                  || j                        | _        | j                  j                  |       y# t        t        f$ r6}t        | j                  |t        j                         d          Y d}~yd}~wt        $ r | j                  d      w xY w)zload(filething)

        Load file information from a filename.

        Args:
            filething (filething)
        Raises:
            mutagen.MutagenError
        r~   Nno appropriate stream found)r/   r   infor   tags
_post_tagsr   IOErrorr   r   sysexc_infor#   r.   	filethingr/   es       r   loadzOggFileType.load  s     ##	=

7+DI

7DII6DIII  )w 	7DKKCLLN1$566 	=++;<<	=s   AA! !B?0,B!!B?T)writableNc                    |j                   }| j                  j                          	 	 | j                  j                  |d        y# t        $ r6}t        | j                  |t        j                         d          Y d}~yd}~wt        $ r | j                  d      w xY w# t        $ r6}t        | j                  |t        j                         d          Y d}~yd}~ww xY w)zdelete(filething=None)

        Remove tags from a file.

        If no filename is given, the one most recently loaded is used.

        Args:
            filething (filething)
        Raises:
            mutagen.MutagenError
        c                      yrm   r   )xs    r   rq   z$OggFileType.delete.<locals>.<lambda>2  s    r   r~   Nr   )r/   r   clear_injectr   r   r   r   r   r#   r   r   s       r   deletezOggFileType.delete  s     ##			7A		!!';7 ;Qq(9:: Akk"?@@A 	7DKKCLLN1$566	7s5   A 	B,B<B" BB" "	C!+,CC!c                     | j                   r   )r   rp   s    r   add_tagszOggFileType.add_tags:  s    kkr   c                    	 | j                   j                  |j                  |       y# t        t        f$ r6}t        | j                  |t        j                         d          Y d}~yd}~wt        $ r | j                  d      w xY w)a)  save(filething=None, padding=None)

        Save a tag to a file.

        If no filename is given, the one most recently loaded is used.

        Args:
            filething (filething)
            padding (:obj:`mutagen.PaddingFunction`)
        Raises:
            mutagen.MutagenError
        r~   Nr   )
r   r   r/   r   r   r   r   r   r   r#   )r.   r   paddingr   s       r   savezOggFileType.save=  sl    	=IIi//9 	7DKKCLLN1$566 	=++;<<	=s   &) B,A))Br   )NN)r   r   r   r   r   r   __annotations__r   r   _mimesr	   r   r   r   r   r   r   r   r   r     s~     
:K!45FZ= =, t7 78 t= =r   r   )r   r$   r   rY   ior   typingr   mutagenr   mutagen._utilr   r   r   r	   r
   r   r   mutagen._filer   mutagen._tagsr   r   r   r   r   r   r   r   <module>r      s\     
       $ 	L 	Pf PfY=( Y=r   