
    i(              	       x   d dl Z d dl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 ddlmZ ddlmZ dd	lmZ dd
lmZ  e       Z e
j*                         Zej.                  j1                  dd      Zej.                  j5                  dd      Zej.                  j5                  dd      Zej.                  j5                  dd      Zej.                  j1                  dd      Zej.                  j5                  dd      Zdee    fdZ!de fdZ"de de fdZ#dde deee e f      de de$fdZ%de deee e f      de fdZ&y)    N)ListDict)Console)config_manager)binary_pathsget_ffmpeg_path   )need_to_force_to_ts)check_duration_v_a)fix_subtitle_extension)capture_ffmpeg_real_timeM3U8_CONVERSIONuse_gpuparam_videoparam_audioparam_finalsubtitle_dispositionsubtitle_disposition_language
ffmpeg_cmdc                     t         r| j                  t                y| j                  t               | j                  t               y)z
    Add encoding parameters to the ffmpeg command.
    
    Parameters:
        ffmpeg_cmd (List[str]): List of the FFmpeg command to modify
    N)PARAM_FINALextendPARAM_VIDEOPARAM_AUDIO)r   s    ]/home/nidran/Documenti/script/streaming-community/StreamingCommunity/core/processors/merge.pyadd_encoding_paramsr   #   s1     +&+&+&    returnc                     	 t         dk(  r5t        j                  dgddd      } | j                  j	                         }nt         dk(  r7	 t        j                  g dddd      } | j                  j	                         }n@t         d	k(  r6t        j                  d
dgddd      } | j                  j	                         }nyd|v ryd|v ryd|v sd|v ryy# t        j
                  t        f$ rZ 	 t        j                  g dddd      } | j                  j	                         }n # t        j
                  t        f$ r Y Y yw xY wY w xY w# t        j
                  t        f$ r Y yw xY w)z
    Detects the GPU device type available on the system.
    
    Returns:
        str: The type of GPU device detected ('cuda', 'vaapi', 'qsv', or 'none').
    linuxlspciT)capture_outputtextcheckwindows)wmicpathwin32_videocontrollergetname)
powershellz-CommandzHGet-WmiObject win32_videocontroller | Select-Object -ExpandProperty Namenonedarwinsystem_profilerSPDisplaysDataTypenvidiacudaintelvaapiamdati)os_type
subprocessrunstdoutlowerCalledProcessErrorFileNotFoundError)resultoutputs     r   detect_gpu_device_typer?   1   s   !g^^WIdUYZF]]((*F	!
"#(`qu  }A  IM  N,,.  ^^%68L$M^bimuyzF]]((*F vf_- 113DE ""'^^  -S  dh  os  {  @F#]]002F"557HI "!" 	". ))+<= ss   AE
 
5C ?A E
  E
 E
 
E
 E.5D$#E$E=E>E
  EEE
 EE
 
E&%E&
video_pathout_pathc                 `   t               g}t        r5t               }t        j	                  d|        |j                  d|g       t        |       r|j                  ddg       |j                  d| g       t        |       |j                  |dg       t        |d      }t	                ||fS )z
    Mux video file using FFmpeg.
    
    Parameters:
        - video_path (str): The path to the video file.
        - out_path (str): The path to save the output file.
    z7[yellow]FFMPEG [cyan]Detected GPU for video join: [red]-hwaccelz-fmpegts-i-yz[yellow]FFMPEG [cyan]Join video)	r   USE_GPUr?   consoleprintr   r
   r   r   )r@   rA   r   gpu_type_hwaccelresult_jsons        r   
join_videorL   \   s     "#$J 13OP`Oabc:'789 :&4*+ tZ() 
# x&' +:7XYK	G[  r   audio_trackslimit_duration_diffc                    d}|D ]  }|j                  d      }|j                  dd      }t        | |      \  }}	}
}t        j                  d| d| d|
dd	|dd
|	dd       |	|kD  set        j                  d| d|	dd| d       d} t	               g}t
        r|j                  dt               g       |j                  d| g       t        |      D ]'  \  }}|j                  d|j                  d      g       ) |j                  ddg       t        dt        |      dz         D ]  }|j                  d| dg        t        |      D ]Y  \  }}|j                  dd      }|j                  d| d| g       |j                  d| d|j                  dd       g       [ t        |       |r|j                  g d       |j                  |dg       t        |d      }t                |||fS )a  
    Joins audio tracks with a video file using FFmpeg.
    
    Parameters:
        - video_path (str): The path to the video file.
        - audio_tracks (list[dict[str, str]]): A list of dictionaries containing information about audio tracks.
            Each dictionary should contain the 'path' and 'name' keys.
        - out_path (str): The path to save the output file.
        - limit_duration_diff (float): Maximum duration difference in seconds.
    Fr'   r*   unknownz$[yellow]    - [cyan]Audio lang [red], [cyan]Path: [red]z, [cyan]Video duration: [red]z.2fzs, [cyan]Audio duration: [red]zs, [cyan]Diff: [red]sz)[yellow]    WARN [cyan]Audio lang: [red]'z*' [cyan]has a duration difference of [red]z(s [cyan]which exceeds the limit of [red]zs.TrC   rE   -map0:vr	   z:az-metadata:s:a:z	language=ztitle=)z	-shortestz-strictexperimentalrF   z[yellow]FFMPEG [cyan]Join audio)r)   r   rH   rI   r   rG   r   r?   	enumeraterangelenr   r   )r@   rM   rA   rN   use_shortestaudio_track
audio_path
audio_lang_diffvideo_durationaudio_durationr   i	lang_coderK   s                   r   join_audiosrc      s    L# 	  __V,
 __VY7
2DZQ[2\/4<ZLH[\f[g  hE  FT  UX  EY  Yw  xF  GJ  wK  K_  `d  eh  _i  ij  k  	l %%MMEj\Q{  }A  BE  |F  Fn  oB  nC  CE  F  GL	  "#$J :'='?@A tZ() $L1 ;;4!89:; vuo&1c,'!+, .6aS8,-. $L1 a;OOFI6	 	^A3/9YK1HIJ^A3/6+//&R[:\9]1^_`a 
# BC x&' +:7XYK	G\;..r   subtitles_listc           
         |D ]  }|d   }t        |      }||d<    t               d| g}t        j                  j	                  |      d   j                         }|dk(  rd}n
|dk(  rd}nd}|D ]  }|d|d   gz  } |g dz  }t        |      D ]  \  }	}|j                  d	|j                  d
d            }
t        j                  d|
 d|j                  dd              |d|	dz    dgz  }|dj                  |	      dj                  |
      gz  } |j                  ddddd|g       t        t        |            D ]  }	|j                  d|	 dg        t        rt        |      dkD  rd}t        |      D ]  \  }	}|j                  d
d      j                         }t        D ]a  }|j                         j!                         }||k(  s|j#                  |      s8t        j                  d|j                  d
              |	} n | n ||j                  d| dg       ||dgz  }t%        |d      }t                ||fS )a  
    Joins subtitles with a video file using FFmpeg.

    Parameters:
        - video_path (str): The path to the video file.
        - subtitles_list (list[dict[str, str]]): A list of dictionaries containing information about subtitles.
            Each dictionary should contain the 'path' key with the path to the subtitle file and the 'name' key with the name of the subtitle.
        - out_path (str): The path to save the output file.
    r'   rE   r	   z.mp4mov_textz.mkvcopy)rS   rT   rS   z0:alanglanguagerP   z'[yellow]    - [cyan]Subtitle lang [red]rQ   rS   z:sz-metadata:s:s:{}ztitle={}z-c:vz-c:az-c:sz-disposition:s:0r   N z3[yellow]    Setting disposition for subtitle: [red]defaultrF   z"[yellow]FFMPEG [cyan]Join subtitle)r   r   osr'   splitextr:   rV   r)   rH   rI   formatr   rW   rX   SUBTITLE_DISPOSITIONSUBTITLE_DISPOSITION_LANGUAGEstrip
startswithr   )r@   rd   rA   subtitleoriginal_pathcorrected_pathr   
output_extsubtitle_codecidxlang_displaydisposition_idxsubtitle_langrh   config_langrK   s                   r   join_subtitlesr~      s    # * (/>)*
 "#T:6J!!(+A.446J V#	v	 # /tXf-..
/ 00J #>2 XX||FHLLY,OP?~M`aiamamntv  bA  aB  C  	Dv#'"~..
)005z7H7H7VWW
	X vvvvv~NO S() :_SE2C89: N 3a 7 '~6 	MC$LLR8>>@M5 "jjl002 K/=3K3KK3XMM$WX`XdXdeoXpWq"rs&)O *	 &0ABINO 8T""J +:7[\K	G[  r   )   )'rm   r7   typingr   r   rich.consoler   StreamingCommunity.utilsr   StreamingCommunity.setupr   r   helper.ex_videor
   helper.ex_audior   helper.ex_subr   capturer   rH   _detect_systemr6   configget_boolrG   get_listr   r   r   rp   rq   strr   r?   rL   floatrc   r~    r   r   <module>r      sp   
   ! 4 B 1 / 1 - )
%,
%
%
'



(
():I
F##,,->N##,,->N##,,->N%,,556GI_`  . 5 5 > >?PRq r 'DI '( (V!!3 !!# !!HB/C B/tDcN/C B/s B/in B/JM!s M!Dc3h4H M!TW M!r   