3
V^Ûp  ã               @   sZ  d dl Z d dlZd dlZddlmZmZmZmZmZ ddl	m
Z
mZmZmZ dd„ ZG dd„ dejƒZd	d	d
dœZd3dd„Zdd„ Zdd„ Zdd„ Zdd„ Zd4dd„Zdd„ Zdd„ Zdd„ ZdZdd „ Zd!d"„ Zd#d$„ Zd%d&„ Z d'd(„ Z!d)d*„ Z"d+d,„ Z#d5d-d.„Z$d7d/d0„Z%ej&ej'eeƒ ej(ej'eƒ ej)ej'eƒ ej*ej'd1ƒ ej+ej'd2ƒ dS )8é    Né   )ÚImageÚ
ImageChopsÚ	ImageFileÚImagePaletteÚImageSequence)Úi8Úi16leÚo8Úo16lec             C   s   | d d… dkS )Né   ó   GIF87aó   GIF89a)r   r   © )Úprefixr   r   ú4/tmp/pip-build-zn8x4q5s/pillow/PIL/GifImagePlugin.pyÚ_accept&   s    r   c               @   sl   e Zd ZdZdZdZdZdd„ Zdd„ Ze	d	d
„ ƒZ
e	dd„ ƒZdd„ Zdd„ Zdd„ Zdd„ Zdd„ ZdS )ÚGifImageFileZGIFzCompuserve GIFFNc             C   s,   | j jdƒ}|r(t|ƒr(| j jt|ƒƒS d S )Nr   )ÚfpÚreadr   )ÚselfÚsr   r   r   Údata7   s    zGifImageFile.datac             C   sJ  | j jdƒ}|d d… dkr$tdƒ‚|d d… | jd< t|dd … ƒt|dd … ƒf| _g | _t|d ƒ}|d	@ d
 }|d@ �rt|d ƒ| jd< | j jd|> ƒ}xxtdt	|ƒdƒD ]d}|d t|| ƒ  koøt||d
  ƒ  koøt||d  ƒkn  s´t
jd|ƒ}| | _| _P q´W | j | _| j jƒ | _d | _d | _| jdƒ d S )Né   r   ó   GIF87aó   GIF89aznot a GIF fileÚversioné   é
   é   r   é€   é   Ú
backgroundé   r   é   ÚRGB)r   r   )r   r   ÚSyntaxErrorÚinfoÚi16Ú_sizeÚtiler   ÚrangeÚlenr   ÚrawÚglobal_paletteÚpaletteÚ_GifImageFile__fpÚtellÚ_GifImageFile__rewindÚ	_n_framesÚ_is_animatedÚ_seek)r   r   ÚflagsÚbitsÚpÚir   r   r   Ú_open=   s*    "
FzGifImageFile._openc             C   sb   | j d kr\| jƒ }yx| j| jƒ d ƒ qW W n" tk
rP   | jƒ d | _ Y nX | j|ƒ | j S )Nr   )r3   r1   ÚseekÚEOFError)r   Úcurrentr   r   r   Ún_frames[   s    

zGifImageFile.n_framesc             C   sj   | j d krd| jd k	r"| jdk| _ nB| jƒ }y| jdƒ d| _ W n tk
rX   d| _ Y nX | j|ƒ | j S )Nr   TF)r4   r3   r1   r;   r<   )r   r=   r   r   r   Úis_animatedg   s    




zGifImageFile.is_animatedc             C   sŽ   | j |ƒsd S || jk r0|dkr&d | _| jdƒ | j}xRt| jd |d ƒD ]:}y| j|ƒ W qL tk
r„   | j|ƒ tdƒ‚Y qLX qLW d S )Nr   r   zno more images in GIF file)Z_seek_checkÚ_GifImageFile__frameÚimr5   r+   r<   r;   )r   ÚframeZ
last_frameÚfr   r   r   r;   x   s    



zGifImageFile.seekc             C   sˆ  |dkrDd| _ d | _ddddg| _d"| _| jj| jƒ d | _d| _n| j	sR| j
ƒ  || jd krltd| ƒ‚|| _g | _| j| _| j r¨| jj| j ƒ x| jƒ r q–W d| _ | jrÀ| j	j| j| jƒ ddlm} || jƒ| _i }�x°| jjdƒ}| pø|dk�r P qà|dk�rV| jjdƒ}| jƒ }t|ƒdk�rˆt|d ƒ}|d@ �rRt|d ƒ|d	< t|dd… ƒd
 |d< d|@ }|d? }|�rB|| _nºt|ƒdk�rÔx8|�rÎd|k�rº|d  |7  < n||d< | jƒ }�q˜W qànnt|ƒdk�rB|| jjƒ f|d< |d d… dk�rB| jƒ }t|ƒdk�rBt|d ƒdk�rBt|dd… ƒ|d< x| jƒ �rR�qDW qà|dkrà| jjdƒ}t|dd … ƒt|dd … ƒ }}	|t|dd … ƒ |	t|dd … ƒ  }
}|
| jd k�sÖ|| jd k�røt|
| jd ƒt|| jd ƒf| _||	|
|f| _t|d ƒ}|d@ dk}|d@ �rN|d@ d }tjd| jjd|> ƒƒ| _t| jjdƒƒ}| jjƒ | _ d||	|
|f| j ||ffg| _P qàqàW yz| jdk �r¦d | _nH| jdk�rÚtj| jƒ tjj d| j| j!d  ƒ| _n| j	�rî| j	jƒ | _| j�r| j"| j| jƒ| _W n t#t$fk
�r$   Y nX | j�s2t%‚x<d#D ]4}||k�rV|| | j!|< n|| j!k�r8| j!|= �q8W d!| _&| j�r„d| _&d S )$Nr   r   zcannot seek to frame %d)Úcopyó   ;ó   !éù   r#   Útransparencyr   Údurationé   r$   éþ   Úcommentéÿ   Ú	extensionr!   s   NETSCAPE2.0Úloopó   ,é	   é   r   r   é@   r    r   r%   ÚgifÚPr"   ÚLéÿÿÿÿ)rH   rI   rL   rN   rO   )'Z_GifImageFile__offsetZdisposeÚdispose_extentr@   r0   r;   r2   Ú_prev_imÚdisposal_methodrA   ÚloadÚ
ValueErrorr*   r   r   ÚpasterD   r.   r/   r   r   r(   r1   r,   ÚsizeÚmaxr)   r   r-   r   Z_decompression_bomb_checkÚcoreÚfillr'   Ú_cropÚAttributeErrorÚKeyErrorr<   Úmode)r   rB   rD   r'   r   Úblockr6   Zdispose_bitsZx0Zy0Úx1Úy1Ú	interlacer7   Úkr   r   r   r5   ˆ   s¾    



 "* "


zGifImageFile._seekc             C   s   | j S )N)r@   )r   r   r   r   r1   $  s    zGifImageFile.tellc             C   s\   t j j| ƒ | jrL| jdkrL| j| j| jƒ}| jj|| j|jdƒƒ | j| _| jj	ƒ | _d S )Nr   ZRGBA)
r   Úload_endrY   rZ   rb   rA   rX   r]   ÚconvertrD   )r   Úupdatedr   r   r   rk   '  s    zGifImageFile.load_endc             C   sB   z4y| j | jkr| j jƒ  W n tk
r0   Y nX W d d | _ X d S )N)r0   r   Úcloserc   )r   r   r   r   Ú
_close__fp4  s    
zGifImageFile._close__fp)Ú__name__Ú
__module__Ú__qualname__ÚformatÚformat_descriptionZ!_close_exclusive_fp_after_loadingr.   r   r:   Úpropertyr>   r?   r;   r5   r1   rk   ro   r   r   r   r   r   /   s    r   rV   rU   )Ú1rV   rU   Fc             C   sp   | j tkr| jƒ  | S tj| j ƒdkrf|r\d}| jrJt| jjƒ d ƒd }| jdtj	|d�S | jdƒS | jdƒS )a  
    Takes an image (or frame), returns an image in a mode that is appropriate
    for saving in a Gif.

    It may return the original image, or it may return an image converted to
    palette or 'L' mode.

    UNDONE: What is the point of mucking with the initial call palette, for
    an image that shouldn't have a palette, or it would be a mode 'P' and
    get returned in the RAWMODE clause.

    :param im: Image object
    :param initial_call: Default false, set to true for a single frame.
    :returns: Image object
    r%   é   r   r#   rU   )r/   ÚcolorsrV   )
re   ÚRAWMODEr[   r   Zgetmodebaser/   r,   Úgetdatarl   ZADAPTIVE)rA   Zinitial_callZpalette_sizer   r   r   Ú_normalize_modeE  s    

r{   c             C   sâ   d}|rjt |tttfƒr(t|dd… ƒ}t |tjƒrjttjjt|j	dd… |j	dd… |j	dd… ƒƒƒ}| j
dkrŽ|s¸| jjdƒdd… }n*|s¨tdd„ tdƒD ƒƒ}tjd|d	�| _	t| |ƒ}|dk	rÖ| j||ƒS || j	_	| S )
at  
    Normalizes the palette for image.
      - Sets the palette to the incoming palette, if provided.
      - Ensures that there's a palette for L mode images
      - Optimizes the palette if necessary/desired.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: Image object
    Ni   rw   i   rU   r%   c             s   s   | ]}|d  V  qdS )r#   Nr   )Ú.0r9   r   r   r   ú	<genexpr>„  s    z%_normalize_palette.<locals>.<genexpr>)r/   )Ú
isinstanceÚbytesÚ	bytearrayÚlistr   Ú	itertoolsÚchainÚfrom_iterableÚzipr/   re   rA   Z
getpaletter+   Ú_get_optimizeZremap_palette)rA   r/   r'   Zsource_paletteÚused_palette_colorsr   r   r   Ú_normalize_palettec  s,    

rˆ   c             C   sÀ   t | dƒ}x$|jjƒ D ]\}}| jj||ƒ qW t||| jƒ}xt|| jƒD ]}|j|ƒ qLW d}t| ƒrr|dB }t	|| d|ƒ dt| ƒf|_
tj||dd| j dt|j fgƒ |jdƒ d S )	NTr   rS   r   rT   ó    )r   r   )r   r   )r{   r'   ÚitemsÚencoderinfoÚ
setdefaultrˆ   Ú_get_global_headerÚwriteÚget_interlaceÚ_write_local_headerZencoderconfigr   Ú_saver^   ry   re   )rA   r   r/   Zim_outrj   Úvr   r6   r   r   r   Ú_write_single_frame�  s    
$r“   c             C   sÊ  | j jd| jjdƒƒ}| j jd| jjdƒƒ}g }d}d }�xºtj| g| j jdg ƒƒD �]œ}�x”tj|ƒD �]„}	t|	jƒ ƒ}	|dkr¨x$|	jj	ƒ D ]\}
}| j j
|
|ƒ qŽW t|	|| j ƒ}	| j jƒ }t|ttfƒrÚ|| |d< t|ttfƒrô|| |d< |d7 }|�rØ|d }|jdƒdk�rj|d k�rdt| | j jd| jjdƒƒƒ}tjd|	j|ƒ}|j|d d	 jƒ |}n|d	 }t|	ƒt|ƒk�r’tj|	|ƒ}ntj|	jd
ƒ|jd
ƒƒ}|jƒ }|�sÜ|rh|d d  |d 7  < qhnd }|j|	||dœƒ qhW qTW t|ƒdk�r�x†|D ]~}|d	 }	|d �sJx"t|	|d ƒD ]}|j|ƒ �q0W d}n*d|d d< |	j|d ƒ}	|d d d… }t||	||d ƒ �q
W dS d| j k�rÆt| j d ttfƒ�rÆt | j d ƒ| j d< d S )NrI   Údisposalr   Zappend_imagesr   r$   r"   rU   rA   r%   r‹   )rA   Úbboxr‹   r•   TÚinclude_color_tablerW   )r   r   )!r‹   Úgetr'   r‚   rƒ   r   ÚIteratorr{   rD   rŠ   rŒ   rˆ   r~   r�   ÚtupleÚ_get_backgroundr   Únewr^   Z
putpaletter/   Ú_get_palette_bytesr   Zsubtract_modulorl   ZgetbboxÚappendr,   r�   rŽ   ZcropÚ_write_frame_dataÚsum)rA   r   r/   rI   r”   Z	im_framesZframe_countZbackground_imZ
imSequenceÚim_framerj   r’   r‹   Úpreviousr"   Zbase_imÚdeltar•   Z
frame_datar   Úoffsetr   r   r   Ú_write_multiple_frames¤  sn    "



r¤   c             C   s   t | ||dd� d S )NT)Úsave_all)r‘   )rA   r   Úfilenamer   r   r   Ú	_save_allñ  s    r§   c             C   s„   d| j ksd| jkr,| j jd| jjdƒƒ}nd }| j jddƒ| j d< | sXt| ||ƒ rdt| ||ƒ |jdƒ t|dƒr€|jƒ  d S )Nr/   ÚoptimizeTrE   Úflush)r‹   r'   r—   r¤   r“   rŽ   Úhasattrr©   )rA   r   r¦   r¥   r/   r   r   r   r‘   õ  s    

r‘   c             C   s$   | j jddƒ}t| jƒdk r d}|S )Nri   r   é   r   )r‹   r—   Úminr^   )rA   ri   r   r   r   r�     s    r�   c             C   s®  d}y|j d }W n tk
r&   Y nJX t|ƒ}d}t||j ƒ}|d k	rpy|j|ƒ}W n tk
rn   d}Y nX d|j krŽt|j d d ƒ}nd}t|j jddƒƒ}|s¶|dks¶|�r|r¾dnd}	|	|d	> O }	|sÖd}| jd
tdƒ tdƒ t|	ƒ t	|ƒ t|ƒ tdƒ ƒ d|j k�r°dt
|j d ƒk�r°| jd
tdƒ ƒ |j d }
t|
tƒ�r`|
jƒ }
x@tdt
|
ƒdƒD ],}|
||d … }| jtt
|ƒƒ| ƒ �qrW | jtdƒƒ d|j k�r|j d }| jd
tdƒ tdƒ d tdƒ tdƒ t	|ƒ tdƒ ƒ |j jdƒ}|�r<t|ƒ}t|ƒ}|�r<|dB }||B }| jdt	|d ƒ t	|d ƒ t	|jd ƒ t	|jd ƒ t|ƒ ƒ |�rœ|�rœ| jt|ƒƒ | jtdƒƒ d S )NFrH   TrI   r   r   r”   r   r$   rF   rG   rR   rL   rK   rM   rO   r!   s   NETSCAPE2.0r#   r–   r    rP   r   )r‹   rd   Úintr†   Úindexr\   r—   rŽ   r
   Úo16r,   r~   ÚstrÚencoder+   rœ   Ú_get_color_table_sizer^   Ú_get_header_palette)r   rA   r£   r6   Ztransparent_color_existsrH   r‡   rI   r”   Zpacked_flagrL   r9   ZsubblockZnumber_of_loopsr–   Úpalette_bytesÚcolor_table_sizer   r   r   r�     sb    

6 

:Br�   c       
      C   sä   | j ƒ }z°t|dƒ�œ}| jdkr8tjd|g|tjd� ntdd|g}dg}tj|tjtjd�}tj||j|tjd�}|jj	ƒ  |j
ƒ }	|	r”tj|	|ƒ‚|j
ƒ }	|	r¬tj|	|ƒ‚W d Q R X W d ytj|ƒ W n tk
rÜ   Y nX X d S )NÚwbr%   Zppmtogif)ÚstdoutÚstderrZppmquantZ256)Ústdinr·   r¸   )Ú_dumpÚopenre   Ú
subprocessÚ
check_callÚDEVNULLÚPopenÚPIPEr·   rn   ÚwaitÚCalledProcessErrorÚosÚunlinkÚOSError)
rA   r   r¦   ÚtempfilerC   Z	quant_cmdZ	togif_cmdZ
quant_procZ
togif_procÚretcoder   r   r   Ú_save_netpbmd  s4    



rÈ   c             C   s�   | j dkrŒ|rŒ|jddƒrŒtp&| j dk}|s<| j| j d	k rŒg }x&t| jƒ ƒD ]\}}|rN|j|ƒ qNW |sˆt|ƒdkrŒt	|ƒt|ƒkrŒ|S dS )
aL  
    Palette optimization is a potentially expensive operation.

    This function determines if the palette should be optimized using
    some heuristics, then returns the list of palette entries in use.

    :param im: Image object
    :param info: encoderinfo
    :returns: list of indexes of palette entries in use, or None
    rU   rV   r¨   r   i   r    N)rU   rV   i   )
re   r—   Ú_FORCE_OPTIMIZEÚwidthÚheightÚ	enumerateZ	histogramr�   r,   r_   )rA   r'   Zoptimiser‡   r9   Úcountr   r   r   r†   ™  s    r†   c             C   sF   dd l }| sdS t| ƒdk r dS t|j|jt| ƒd dƒƒƒd S d S )Nr   rQ   r   r#   r$   )Úmathr,   r­   ÚceilÚlog)r´   rÎ   r   r   r   r²   ¾  s    r²   c             C   s<   t | ƒ}d|> t| ƒd  }|dkr8| tdƒd | 7 } | S )zä
    Returns the palette, null padded to the next power of 2 (*3) bytes
    suitable for direct inclusion in the GIF header

    :param palette_bytes: Unpadded palette bytes, in RGBRGB form
    :returns: Null padded palette
    r$   r#   r   )r²   r,   r
   )r´   rµ   Zactual_target_size_diffr   r   r   r³   Ê  s
    r³   c             C   s   | j j S )zš
    Gets the palette for inclusion in the gif header

    :param im: Image object
    :returns: Bytes, len<=768 suitable for inclusion in gif header
    )r/   )rA   r   r   r   rœ   Ü  s    rœ   c             C   s&   d}|r"|}t |tƒr"| jj|ƒ}|S )Nr   )r~   r™   r/   Zgetcolor)rA   ZinfoBackgroundr"   r   r   r   rš   æ  s    
rš   c             C   sÜ   d}xrdD ]V}|r
||kr
|dkr.|| dks
|dkrZdt || ƒ  koPdkn   rZq
d	}P q
W | jjd
ƒd	krxd	}t| |jdƒƒ}t| ƒ}t|ƒ}d| t| jd ƒ t| jd ƒ t|d ƒt|ƒtdƒ t	|ƒgS )z2Return a list of strings representing a GIF headers   87arH   rI   rO   rL   r   r   rM   s   89ar   r"   s   GIFr    )rH   rI   rO   rL   )
r,   r'   r—   rš   rœ   r²   r¯   r^   r
   r³   )rA   r'   r   ZextensionKeyr"   r´   rµ   r   r   r   r�   ò  s"    
*"
r�   c             C   sR   zF||_ t| ||dƒ tj|| dd|j dt|j fgƒ | jdƒ W d |` X d S )Nr   rT   r‰   )r   r   )r‹   r�   r   r‘   r^   ry   re   rŽ   )r   r    r£   Úparamsr   r   r   rž     s     rž   c             C   sd   t | |ƒ}|dkri }d|kr6d| jkr6| jd |d< t| ||ƒ}|j| _|j| _t| |ƒ}||fS )a  
    Legacy Method to get Gif data from image.

    Warning:: May modify image data.

    :param im: Image object
    :param palette: bytes object containing the source palette, or ....
    :param info: encoderinfo
    :returns: tuple of(list of header items, optimized palette)

    Nr"   )r†   r'   rˆ   r/   rA   r�   )rA   r/   r'   r‡   Zim_modÚheaderr   r   r   Ú	getheader-  s    

rÓ   c             K   s0   G dd„ dƒ}| j ƒ  |ƒ }t|| ||ƒ |jS )a„  
    Legacy Method

    Return a list of strings representing this image.
    The first string is a local image header, the rest contains
    encoded image data.

    :param im: Image object
    :param offset: Tuple of (x, y) pixels. Defaults to (0,0)
    :param \**params: E.g. duration or other encoder info parameters
    :returns: List of Bytes containing gif encoded frame data

    c               @   s   e Zd Zg Zdd„ ZdS )zgetdata.<locals>.Collectorc             S   s   | j j|ƒ d S )N)r   r�   )r   r   r   r   r   rŽ   ]  s    z getdata.<locals>.Collector.writeN)rp   rq   rr   r   rŽ   r   r   r   r   Ú	CollectorZ  s   rÔ   )r[   rž   r   )rA   r£   rÑ   rÔ   r   r   r   r   rz   K  s
    rz   z.gifz	image/gif)F)F)NN©r   r   )rÕ   ),r‚   rÃ   r¼   Ú r   r   r   r   r   Ú_binaryr   r	   r(   r
   r   r¯   r   r   ry   r{   rˆ   r“   r¤   r§   r‘   r�   r�   rÈ   rÉ   r†   r²   r³   rœ   rš   r�   rž   rÓ   rz   Zregister_openrs   Zregister_saveZregister_save_allZregister_extensionZregister_mimer   r   r   r   Ú<module>   sB   	  
,M

T2%
'

!