
    g5jT                        d 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
 ddlmZmZ ddlmZ d	d
lmZ d	dlmZmZmZmZ 	 ddlZi dddej8                  ej:                  fdddej8                  ej:                  fdddej8                  ej<                  fdddej8                  ej:                  fdddej8                  ej:                  fdddej8                  ej<                  fdddej>                  ej>                  fdddej>                  ej>                  fdd	dej>                  ej>                  fdd	dej>                  ej>                  fdd	dej>                  ej>                  fdddej8                  ej:                  fdddej8                  ej:                  fdddej8                  ej<                  fd ddej8                  ej:                  fd!ddej8                  ej:                  fd"ddej8                  ej<                  fi d#ddej>                  ej>                  fd$ddej>                  ej>                  fd%d	dej>                  ej>                  fd&d	dej>                  ej>                  fd'd	dej>                  ej>                  fd(dd)ej8                  ej:                  fd*dd)ej8                  ej:                  fd+dd)ej8                  ej<                  fd,dd)ej8                  ej:                  fd-dd)ej8                  ej:                  fd.dd)ej8                  ej<                  fd/dd)ej>                  ej>                  fd0dd)ej>                  ej>                  fd1d	d)ej>                  ej>                  fd2d	d)ej>                  ej>                  fd3d	d)ej>                  ej>                  fd4dd5ej8                  ej@                  fdd5ej8                  ej@                  fdd5ej8                  ejB                  fdd5ej8                  ej@                  fdd5ej8                  ej@                  fdd5ej8                  ejB                  fdd5ej>                  ej>                  fdd5ej>                  ej>                  fd	d5ej>                  ej>                  fdd5ejD                  ejF                  fd6	Z$d7d8d9d:Z%d9d8d7d;Z&d<e'd=dfd>Z(d<e'd=e)dz  fd?Z*d<e'd=e)fd@Z+d]d<e'dAe)dz  dBe,d=e)dz  fdCZ-d]d<e'dBe,d=e)dz  fdDZ.d=e/fdEZ0d^d=e1fdFZ2dGe3e'   d=e1dz  fdHZ4dGe3e'   d=e1dz  fdIZ5dJej                  d=e1dz  fdKZ6dJej                  d=e1dz  fdLZ7dJej                  d=ej                  fdMZ8 G dN dOe      Z9dJej                  dPe)d=ej                  fdQZ:dRe)dz  d=e)fdSZ;dTe<dz  fdUZ=d=e'fdVZ> G dW dX      Z?e G dY dZ             Z@d[e/e
z  d=dfd\ZAy# e$ rZd	dlmZ  ee      ZY dZ[dZ[ww xY w)_zoDifferent miscellaneous helper functions.

Mostly for internal use, so prototypes can change between versions.
    N)	dataclass)IntEnum)ceil)Path)packunpack)Image   )options)HeifChannel
HeifChromaHeifColorspaceHeifCompressionFormat)DeferredErrorzBGRA;16      zBGRa;16zBGR;16   zRGBA;16zRGBa;16zRGB;16zLA;16   zLa;16zL;16zI;16I;16LzBGRA;12   zBGRa;12zBGR;12zRGBA;12zRGBa;12zRGB;12zLA;12zLa;12zL;12zI;12zI;12LzBGRA;10
   zBGRa;10zBGR;10zRGBA;10zRGBa;10zRGB;10zLA;10zLa;10zL;10zI;10zI;10LRGBA   )	RGBaRGBBGRABGRaBGRLALaLYCbCri  i  i  )z4:4:4z4:2:2z4:2:0)r
   r   r   inforeturnc                 R    t         j                  | j                        }|||d<   yy)zYConverts `chroma` value from `c_image` to useful values and stores them in ``info`` dict.Nchroma)LIBHEIF_CHROMA_MAPgetr&   )c_imager#   r&   s      B/var/www/html/qr/venv/lib/python3.12/site-packages/pi_heif/misc.pysave_colorspace_chromar+   W   s,      ##GNN3FX     c                     t        | d      S )a  Reset orientation in ``EXIF`` to ``1`` if any orientation present.

    Removes ``XMP`` orientation tag if it is present.
    In Pillow plugin mode, it is called automatically for images.
    When ``pi_heif`` used in ``standalone`` mode, if you wish, you can call it manually.

    .. note:: If there is no orientation tag, this function will not add it and do nothing.

        If both XMP and EXIF orientation tags are present, EXIF orientation tag will be returned,
        but both tags will be removed.

    :param info: `info` dictionary from :external:py:class:`~PIL.Image.Image` or :py:class:`~pi_heif.HeifImage`.
    :returns: Original orientation or None if it is absent.
    T_get_orientation)r#   s    r*   set_orientationr0   _   s     D$''r,   c                 &    t        | d      }|dS |S )NFr
   r.   )r#   image_orientations     r*   _get_orientation_for_encoderr3   q   s     (u5!)1@/@@r,   exif_orientationresetc                    d}| j                  d      r| d   j                  dd      }|d   rd }dD ]  }	 |d   j                  |      } n |rt	        j
                  d|      }|r>t        |d         }|r.t	        j                  dd	|      }t	        j                  d
d	|      }dk7  s|dk7  r5dj                  |j                  d      t        |      dkD  rdndg      | d<   ||dk7  r|S d S # t        $ r Y w xY w)Nr
   xmp    r   )utf-8latin1ztiff:Orientation(="|>)([0-9])r   ztiff:Orientation="([0-9])" z,<tiff:Orientation>([0-9])</tiff:Orientation>r9   r,   )r(   rsplitdecode	Exceptionresearchintsubjoinencodelen)r#   r4   r5   xmp_orientationxmp_datadecoded_xmp_dataencodingmatchs           r*   _get_orientation_xmprK   v   s'   Oxx;%%gq1A;#/ '/{'9'9('C$  		"BDTU&)%(mO+-662OQSUe+f(+-662acegw+x(w&/Q*>"%((,<,C,CG,LY\]eYfijYjgps+t"uDK.6?a;O?YUYY ! s   C//	C;:C;c                 V   d }| j                  d      r	 | d   }d}|j                  d      rd}|dd  }|dd dk(  rd	nd
}t        |dz   |dd       d   }t        |dz   |||dz          d   }|dz   }t        |      D ]  }	|d|	z  z   }t        |dz   |||dz          d   dk7  r'||dz   |dz    }
t        |dz   |
dd       d   }|dk7  sM|}|s n8|dz   }|r|dz  }t	        |dz   d      }| d   d | |z   | d   |dz   d  z   | d<    n t        | ||      }|xs |S # t
        $ r Y w xY w)NexifF   Exif  T   r   r   s   II<>r!   r   r   Hr   i  r
   )r5   )r(   
startswithr   ranger   r>   rK   )r#   r5   original_orientationtif_tagskipped_exif00endian_markpointer	tag_countoffsettag_nvaluet_original_orientationp_valuenew_orientationrF   s                  r*   r/   r/      s   xx	6lG"N!!/2!%!!"+!(1!<##K[3.!=a@G{S0''GaK2PQRSTIq[Fy)  2:-++WWw{-KLQOSVV!gl;)/c0A51:)Nq)Q&)Q.+A( %kG%1&*;+<a&@O#'<#9O#KdSYl[bef[f[hNi#iDL$ +41EUSO222  		s   B4D 
>D 	D('D(c                 j    t        | d      dd }|r"|dk(  ry|dk(  ry|dv ry	|d
v ry|dk(  ry|dk(  ryy)a  Gets the MIME type of the HEIF(or AVIF) object.

    :param fp: A filename (string), pathlib.Path object, file object or bytes.
        The file object must implement ``file.read``, ``file.seek`` and ``file.tell`` methods,
        and be opened in binary mode.
    :returns: "image/heic", "image/heif", "image/heic-sequence", "image/heif-sequence",
        "image/avif", "image/avif-sequence" or "".
    r   r   Ns   avifz
image/avifs   aviszimage/avif-sequence)s   heics   heixs   heims   heisz
image/heic)s   hevcs   hevxs   hevms   hevszimage/heic-sequences   mif1z
image/heifs   msf1zimage/heif-sequencer;   )
_get_bytes)fp
heif_brands     r*   get_file_mimetypere      sa     B#AB'J  (====(  (r,   c                    t        | t        t        f      r5t        j                  | d      5 }|j                  |xs d      cd d d        S t        | d      rTt        | d      r| j                         nd }| j                  |xs d      }|t        | d      r| j                  |       |S t        |       d | S # 1 sw Y   wxY w)Nrbreadtellseek)

isinstancestrr   builtinsopenri   hasattrrj   rk   bytes)rc   lengthfiler[   results        r*   rb   rb      s    "sDk"]]2t$ 	+99V\r*	+ 	+r6%b&1t2&'"f"5GGFO9Wf	+ 	+s   B::Cmetadatac                 R   d }g }t        |       D ]  \  }}|d   dk(  s|j                  |       t        j                  |d   d d dd      }|dz  }t	        |d         |z
  dk  rd}n|dk\  r|d   |dz
  | d	k(  r|dz  }|d   |d  }|r}|s|} t        |      D ]  }| |=  |S )
NtypeExifdatar   bigF)	byteordersignedrO   rN   )	enumerateappendrA   
from_bytesrE   reversed)ru   rt   purgeimd_block	skip_sizery   s          r*   _retrieve_exifr      s    FE * 8Fv%LLOx'7';uUZ[INI8F#$y0A5	aHV$4Y]Y$OSb$bQ	F#IJ/Dd e_ QKMr,   c                     d }g }t        |       D ]'  \  }}|d   dk(  s|j                  |       |r#|d   }) t        |      D ]  }| |=  |S )Nrw   mimery   )r}   r~   r   )ru   rt   r   r   r   s        r*   _retrieve_xmpr      sj    FE * *8Fv%LLO!&)	*
 e_ QKMr,   imgc                     d| j                   v r| j                   d   S t        | d      r"| j                         }|r|j                         S y )NrM   getexif)r#   rp   r   tobytes)r   rM   s     r*   _exif_from_pillowr      sD    xxsI{{}<<>!r,   c                     d }d| j                   v r| j                   d   }nd| j                   v r| j                   d   }t        |t              r|j                  d      }|S )Nr7   zXML:com.adobe.xmpr9   )r#   rl   rm   rD   )r   im_xmps     r*   _xmp_from_pillowr     sX    F%		(-.&#w'Mr,   c                    | j                   dk(  r4| j                  j                  dd       dnd}| j                  |      } | S | j                   dk(  r| j                  d      } | S | j                   dk(  r| j                  d	      } | S | j                   d
k(  r| j                  d      } | S | j                   dk(  r| j                  d      } | S )NPtransparencyr   r   )modeIr   1r!   CMYKr"   )r   r#   r(   convert)r   r   s     r*   _pil_to_supported_moder     s    
xx3nd;GvUkktk$ J 
Skkwk' J 
Skksk#
 J	 
V	kkvk& J 
W	kkuk%Jr,   c                   ,    e Zd ZdZdZdZdZdZdZdZ	dZ
y	)
	TransposezkTemporary workaround till we support old Pillows, remove this when a minimum Pillow version will have this.r   r
   r   r   r      rO   N)__name__
__module____qualname____doc__FLIP_LEFT_RIGHTFLIP_TOP_BOTTOM	ROTATE_90
ROTATE_180
ROTATE_270	TRANSPOSE
TRANSVERSE r,   r*   r   r     s(    uOOIJJIJr,   r   orientationc                 "   t         j                  t         j                  t         j                  t         j                  t         j
                  t         j                  t         j                  dj                  |      }|| j                  |      S | S )N)r   r   r   r   rO      r   )
r   r   r   r   r   r   r   r   r(   	transpose)r   r   methods      r*   _rotate_pilr   +  su     $$$$ 
c+  }}V$$Jr,   primary_indexc                     | D cg c]  }|j                   j                  dd        }}|d}t        |      D ]
  \  }}|s	|} |S |dk(  s|t        |      k\  rt        |      dz
  }|S c c}w )NprimaryFr   rh   r
   )r#   r(   r}   rE   )some_iteratorr   _primary_attrsr   vs         r*   _get_primary_indexr   <  s    ;HIaQVVZZ	51IMIm, 	"DAq !	"
  
"	]1C CM*Q. Js   #A+valuesc                 8    | r| d   | d   | d   | d   | d   dS d S )Nr   r
   r   r   r   )focal_length_xfocal_length_yprincipal_point_xprincipal_point_yskewr   )r   s    r*   __get_camera_intrinsic_matrixr   H  s@      %Qi$Qi!'!'1I	

 
r,   c                 h    i }t        | j                        }|r||d<   | j                  }|r||d<   |S )Ncamera_intrinsic_matrixcamera_extrinsic_matrix_rot)r   r   r   )r)   rr   r   s       r*   _get_heif_metar   V  sE    
A;G<[<[\'>
#$")"E"E"+F
'(Hr,   c                   |    e Zd ZdZdefdZdeeef   deddfdZ	d	e
j                  ddfd
Zdeeef   fdZddZy)	CtxEncodez0Encoder bindings from python to python C module.compression_formatc                    |j                  dt        j                        }t        j                  ||dn|t        j
                  j                  |t        j                  k(  rdndd            | _        |j                  di       }d }d|v rt        j                  |d         }||j                  d      }|r||d<   |j                         D ]<  \  }}| j                  j                  |t        |t              r|n
t        |             > y )	NqualityHEIFAVIFr;   
enc_paramssubsamplingr&   )r(   r   QUALITY_pi_heifCtxWritePREFERRED_ENCODERr   HEVC	ctx_writeSUBSAMPLING_CHROMA_MAPitemsset_parameterrl   rm   )selfr   kwargsr   r   r&   keyr]   s           r*   __init__zCtxEncode.__init__d  s    **Y8!**/Bw%%))4FJ_JdJd4d&jprtu

 ZZb1
F"+//}0EFF>ZZ)F#)Jx $**, 	_JCNN((z%7MeSVW\S]^	_r,   sizer   r$   Nc                    |d   dk  s|d   dk  rt        d      t        |   d   }|dk(  rdn|j                  dd      }|dk(  rt        j                  rdnd}t        |j                  d	
      d   d   dk(        }| j                  j                  |t        |   d   t        |   d   |      }t        |   d   dk(  r5|j                  |||||j                  dd      t        j                         nmt        |   d   dk(  r&|j                  |||||j                  dd             n8|j                  |||||j                  d      dk7  |j                  dd              | j                  ||fi | y)zAdds image to the encoder.r   r
   zEmpty images are not supported.r   	bit_depthr   r   r   ;)seprh   ar   r   strider   N)
ValueError	MODE_INFOr(   r   SAVE_HDR_TO_12_BITrA   splitr   create_imageadd_plane_lr   	CHANNEL_Yadd_plane_la	add_planefind_finish_add_image)	r   r   r   ry   r   bit_depth_inbit_depth_outpremultiplied_alphaim_outs	            r*   	add_imagezCtxEncode.add_imagev  su   7a<47a<>?? q))Q.FJJ{B4OB")"<"<B"M!$***"5a"8"<"CD,,T9T?13EyQUWXGY[noT?1"t]L$

S[]^H_alavavwt_Q1$m\4T\^_I`aT=,diiPUFVZ\F\^d^h^hiqst^uvvt6v6r,   r   c                    | j                   j                  |j                  t        |j                     d   t        |j                     d   d      }t
        j                  t
        j                  t
        j                  fD ]J  }|j                  |j                  ddt        |j                  |            |j                  dd      |       L  | j                  ||j                  fi | y)z*Adds image in `YCbCR` mode to the encoder.r   r   r   r   r   N)r   r   r   r   r   r   r   
CHANNEL_CB
CHANNEL_CRr   rq   getdatar(   r   )r   r   r   r   r   s        r*   add_image_ycbcrzCtxEncode.add_image_ycbcr  s     ,,SXXy7J17MyY\YaYaObcdOeghi'')?)?AWAWX 	bAsxxAuS[[^/DfjjQY[\F]_`a	bvsxx:6:r,   c           
         j                  d      }|"|j                  j                  dd      |       j                  d      r# |j                  dD cg c]
  }d   |    c}  j                  d      }|r|j                  |d   |d          j                  d	d      }j                  d
t        j
                        }d}	t        fd|	D              }
|rj                  d      s|
s	d}d}d}d}nHj                  dd      }j                  dd      }j                  dd      }j                  dd      }|j                  | j                  j                  dd      ||||||       j                  d      }|Ft        |t        j                        r|j                         }|j                  | j                  |       j                  d      }||j                  | j                  |       j                  dg       D ])  }|j                  | j                  |d   |d   |d          + j                  dg       D ]7  }t!        |      |cxkD  rdkD  sn |j#                  | j                  ||       9 y c c}w )Nicc_profileicc_profile_typeprofnclx_profile)color_primariestransfer_characteristicsmatrix_coefficientsfull_range_flagpixel_aspect_ratior   r
   r2   save_nclx_profilec              3   &   K   | ]  }|v  
 y wNr   ).0kr   s     r*   	<genexpr>z.CtxEncode._finish_add_image.<locals>.<genexpr>  s     ?V?s      rO   r   rh   r   r   r   r   FrM   r7   ru   rw   content_typery   
thumbnailsr   )r(   set_icc_profileset_nclx_profileset_pixel_aspect_ratior   SAVE_NCLX_PROFILEanyrD   r   rl   r	   rx   r   set_exifset_xmpset_metadatamaxencode_thumbnail)r   r   r   r   r   r   r   r2   	save_nclx	nclx_keyshas_explicit_nclxr   r   r   r   rM   r7   ru   	thumb_boxs      `               r*   r   zCtxEncode._finish_add_image  s|   jj/"""6::.@&#I;W::n%#F## w >*1- $ZZ(<=))*<Q*?ASTUAVW"JJ':A>JJ2G4M4MN	m	?Y?? VZZ7@QO')$"#O$jj):B?O'-zz2Lb'Q$"(**-BB"G$jj):B?ONNJJy%($		
 zz&!$

+||~OODNND1jj?NN4>>3/

:r2 	nH0@(>BZ\dek\lm	n  L"5 	VI4y9(q(''	CTU	Vos   J	c                     | j                   j                         }t        |t        t        f      rt	        |      j                  |       yt        |d      r|j                  |       yt        d      )z?Ask encoder to produce output based on previously added images.writez=`fp` must be a path to file or an object with `write` method.N)	r   finalizerl   rm   r   write_bytesrp   r  	TypeError)r   rc   ry   s      r*   savezCtxEncode.save  sU    ~~&&(b3+&H  &R!HHTN[\\r,   )r$   N)r   r   r   r   r   r   tuplerA   rm   r   r	   r   r   r  r   r,   r*   r   r   a  sl    :_+@ _$7eCHo 7S 7T 7(;5;; ;T ;AVeCHo AVF]r,   r   c                   T    e Zd ZdZdedeeef   defdZe	d        Z
e	defd       Zy	)
	MimCImagezMimicry of the HeifImage class.r   r   ry   c                    || _         || _        |j                  d|d   t        |   d   z  t	        t        |   d   dz        z        | _        || _        g | _        d | _        g | _	        g | _
        g | _        d| _        t        j                  j                  | _        t"        j                  j                  | _        d | _        d | _        d | _        y )Nr   r   r
   r   F)r   r   r(   r   r   r   ry   ru   color_profiler	  depth_image_listaux_image_idsr   r   	UNDEFINEDr]   r&   r   
colorspacer   r   r   )r   r   r   ry   r   s        r*   r   zMimCImage.__init__  s    		!::hQ)D/!:L0LtT]^bTcdeTfijTjOk0kl	$&!%'&((* **00(2288"&'+$+/(r,   c                 2    | j                   | j                  fS )zMimicry of c_image property.)r   r   r   s    r*   	size_modezMimCImage.size_mode  s     yy$))##r,   r$   c                 .    t         | j                     d   S )z%Return bit-depth based on image mode.r
   )r   r   r(  s    r*   r   zMimCImage.bit_depth  s     #A&&r,   N)r   r   r   r   rm   r  rA   rq   r   propertyr)  r   r   r,   r*   r   r     sV    )0S 0c3h 0u 0" $ $ '3 ' 'r,   r   plugin_pathc                 .    t        j                  |        y)zLoad specified LibHeif plugin.N)r   load_plugin)r,  s    r*   load_libheif_pluginr/    s    %r,   )Fr  )Br   rn   r?   dataclassesr   enumr   mathr   pathlibr   structr   r   PILr	   r;   r   	constantsr   r   r   r   r   ImportErrorex_deffered_errorr   r   INTERLEAVED_RRGGBBAA_LEINTERLEAVED_RRGGBB_LE
MONOCHROMEINTERLEAVED_RGBAINTERLEAVED_RGBYCBCR
CHROMA_444r   r   r'   dictr+   rA   r0   r3   boolrK   r/   rm   re   rq   rb   listr   r   r   r   r   r   r   r   r  r   r   r   r   r/  r   r,   r*   <module>rD     s  
  	 !       U U!-2~)):+M+MN- 2~)):+M+MN- q"n((**J*JK	-
 2~)):+M+MN- 2~)):+M+MN- q"n((**J*JK- a^..
0E0EF- a^..
0E0EF- QN--z/D/DE- QN--z/D/DE- a^..
0E0EF- 2~)):+M+MN- 2~)):+M+MN- q"n((**J*JK-  2~)):+M+MN!-" 2~)):+M+MN#-$ q"n((**J*JK%-& a^..
0E0EF'-( a^..
0E0EF)-* QN--z/D/DE+-, QN--z/D/DE--. a^..
0E0EF/-0 2~)):+M+MN1-2 2~)):+M+MN3-4 q"n((**J*JK5-6 2~)):+M+MN7-8 2~)):+M+MN9-: q"n((**J*JK;-< a^..
0E0EF=-> a^..
0E0EF?-@ QN--z/D/DEA-B QN--z/D/DEC-D a^..
0E0EFE-F Q>%%z'B'BCG-H >%%z'B'BCq.$$j&@&@A>%%z'B'BC>%%z'B'BCq.$$j&@&@Aa**J,A,A
Ba**J,A,A
B
Q)):+@+@	AN((**?*?@Y-	`   

  $  4  ($ (3: ($At A A
Zt ZsTz Z$ Z[^ae[e Z2 34  3  3t  3FS 4
5 
T$Z EDL (
DJ 
54< 
5;; 54< %++ %$,    	 	U[[ s u{{ "	S4Z 	C 	%$, t }] }]@ ' ' '>&S4Z &D &Y  !.R H!s   W% %X*W>>X