
    дhKI                        S r SSKJr  SSKJr  SSKJr  SSKJrJ	r	  SSK
JrJrJr  SSKJrJrJrJrJrJrJrJrJrJrJrJrJr  SSKrSSKr " S	 S
\\5      r " S S\\5      r " S S\\5      r  " S S\\\5      r! " S S\\5      r"g)a  
Stream Models for Stream Processor Application

This module contains Django models for managing streaming operations,
including channel configuration, stream sessions, HLS segments,
and monitoring data. These models provide the data structure for
the entire stream processing workflow.
    )models)User)timezone)MinValueValidatorMaxValueValidator)TimestampedModel	UUIDModelStatusModel)validate_hls_urlvalidate_directory_pathvalidate_name_formatvalidate_slug_formatvalidate_segment_durationvalidate_max_segmentsvalidate_retry_attemptsvalidate_video_dimensionsvalidate_video_bitratevalidate_audio_bitratevalidate_sample_ratevalidate_audio_channelsvalidate_framerateNc                      \ rS rSrSr\R                  " SS\/SS9r\R                  " SS\
/SS9r\R                  " S\/S	S
9r\R                  " SSS9r\R"                  " SSSS9r\R                  " S\/SS
9r\R*                  " S\/SS9r\R*                  " S\/SS9r\R*                  " S\/SS9r\R*                  " S\" S5      \" S5      /SS9r\R>                  " \ \RB                  SSS9r" " S S5      r#S  r$S! r%S" r&S# r'S$ r(S%r)g&)'Channel   a  
Model representing a streaming channel configuration.

A channel defines the source stream URL, encoding parameters,
and output configuration for a specific streaming operation.
Multiple stream sessions can be associated with a single channel.

Attributes:
    name (CharField): Human-readable name for the channel
    slug (SlugField): URL-friendly identifier for the channel
    hls_url (URLField): Source HLS stream URL to capture
    description (TextField): Optional description of the channel
    is_active (BooleanField): Whether the channel is currently active
    output_directory (CharField): Directory path for stream output
    segment_duration (PositiveIntegerField): HLS segment duration in seconds
    max_segments (PositiveIntegerField): Maximum number of segments to keep
    retry_attempts (PositiveIntegerField): Number of retry attempts on failure
    retry_interval (PositiveIntegerField): Seconds between retry attempts
    created_by (ForeignKey): User who created this channel
d   Tz#Human-readable name for the channel)
max_lengthunique
validators	help_textz'URL-friendly identifier for the channel  z Source HLS stream URL to capture)r   r   r   z+Optional description of the channel contentblankr   z(Whether this channel is currently activedefaultdb_indexr      z&Directory path for stream output files   z'Duration of each HLS segment in secondsr$   r   r   
   z.Maximum number of segments to keep in playlist   z+Number of retry attempts on capture failure   i,  z&Seconds to wait between retry attemptschannelszUser who created this channel	on_deleterelated_namer   c                       \ rS rSrSrSrS/r\R                  " S/S9\R                  " S/S9\R                  " S/S9/r	S	r
g
)Channel.Metaz   r   Channelsnameslugfields	is_active
created_at N__name__
__module____qualname____firstlineno__verbose_nameverbose_name_pluralorderingr   Indexindexes__static_attributes__r:       ?C:\Users\brahi\OneDrive\Desktop\Code\src\apps\streams\models.pyMetar1   z   sE     (8LL)LL.LL/
rF   rH   c                     U R                   $ )z%String representation of the channel.)r4   selfs    rG   __str__Channel.__str__   s    yyrF   c                 j    [         R                  R                  U R                  U R                  5      $ )z*Get the full output path for this channel.)ospathjoinoutput_directoryr5   rJ   s    rG   get_output_pathChannel.get_output_path   s!    ww||D11499==rF   c                 ^    [         R                  R                  U R                  5       S5      $ )z)Get the HLS output path for this channel.hls)rO   rP   rQ   rS   rJ   s    rG   get_hls_pathChannel.get_hls_path   s     ww||D002E::rF   c                 ^    [         R                  R                  U R                  5       S5      $ )z)Get the path to the master playlist file.zplaylist.m3u8)rO   rP   rQ   rW   rJ   s    rG   get_playlist_pathChannel.get_playlist_path   s     ww||D--/AArF   c                 P    U R                   R                  SS9R                  5       $ )z9Get the currently active stream session for this channel.active)status)sessionsfilterfirstrJ   s    rG   get_active_sessionChannel.get_active_session   s#    }}##8#4::<<rF   r:   N)*r<   r=   r>   r?   __doc__r   	CharFieldr   r4   	SlugFieldr   r5   URLFieldr   hls_url	TextFielddescriptionBooleanFieldr8   r   rR   PositiveIntegerFieldr   segment_durationr   max_segmentsr   retry_attemptsr   r   retry_interval
ForeignKeyr   CASCADE
created_byrH   rL   rS   rW   rZ   rb   rE   r:   rF   rG   r   r      s   , ()7	D ();	D oo$%4G ""?K ##<I ''+,: 22-.; ..)*BL 00+,?N 00%a(*;C*@A:N ""..1	J
 
>;B=rF   r   c                      \ rS rSrSr\R                  " SSSS9r\R                  " SSS	S
9r\R                  " SSSS
9r	\R                  " S\" S5      \" S5      /SS9r\R                  " SSSS
9r\R                  " SSSS
9r\R                  " SS/ SQSS9r\R                  " SS/ SQSS9r\R                  " SS/ SQS S9r\R                  " SS!S"S
9r " S# S$5      rS% rS&rg')(VideoConfiguration   a  
Model for video encoding configuration parameters.

This model stores video encoding settings that can be applied
to stream processing operations, allowing for different quality
profiles and encoding options.

Attributes:
    name (CharField): Name for this video configuration
    resolution (CharField): Video resolution (e.g., "1920x1080")
    aspect_ratio (CharField): Video aspect ratio (e.g., "16:9")
    frame_rate (PositiveIntegerField): Video frame rate in FPS
    min_bitrate (CharField): Minimum video bitrate
    max_bitrate (CharField): Maximum video bitrate
    codec (CharField): Video codec to use
    preset (CharField): Encoding preset for speed/quality trade-off
    profile (CharField): Video profile setting
    level (CharField): Video level setting
2   Tz!Name for this video configurationr   r   r      1280x720z!Video resolution (width x height)r   r$   r   r)   z16:9zVideo aspect ratio   r+   x   z%Video frame rate in frames per secondr(   2000kz%Minimum video bitrate (e.g., '2000k')4000kz%Maximum video bitrate (e.g., '4000k')h264))r   zH.264)h265zH.265)vp9VP9zVideo codec to use for encodingr   r$   choicesr   medium)	)	ultrafastz
Ultra Fast)	superfastz
Super Fast)veryfastz	Very Fast)fasterFaster)fastFast)r   Medium)slowSlow)slowerSlower)veryslowz	Very Slowz+Encoding preset for speed/quality trade-offmain))baselineBaseline)r   Main)highHighzVideo profile settingz3.1z(Video level setting (e.g., '3.1', '4.0')c                   "    \ rS rSrSrSrS/rSrg)VideoConfiguration.Metai  zVideo ConfigurationzVideo Configurationsr4   r:   Nr<   r=   r>   r?   r@   rA   rB   rE   r:   rF   rG   rH   r         ,48rF   rH   c                 :    U R                    SU R                   S3$ )z1String representation of the video configuration. ())r4   
resolutionrJ   s    rG   rL   VideoConfiguration.__str__  s    ))Bt/q11rF   r:   N)r<   r=   r>   r?   rd   r   re   r4   r   aspect_ratiorl   r   r   
frame_ratemin_bitratemax_bitratecodecpresetprofilelevelrH   rL   rE   r:   rF   rG   ru   ru      sJ   * 5D !!5J ##&L ,,%a(*;C*@A9J ""9K ""9K 

 4	E 

 @F" 

 *	G <E 
2rF   ru   c                      \ rS rSrSr\R                  " SSSS9r\R                  " SS/ S	QS
S9r\R                  " SSSS9r	\R                  " S/ SQSS9r\R                  " S/ SQSS9r\R                  " SSS9r " S S5      rS rSrg)AudioConfigurationi  a7  
Model for audio encoding configuration parameters.

This model stores audio encoding settings that can be applied
to stream processing operations, allowing for different audio
quality profiles and encoding options.

Attributes:
    name (CharField): Name for this audio configuration
    codec (CharField): Audio codec to use
    bitrate (CharField): Audio bitrate setting
    sample_rate (PositiveIntegerField): Audio sample rate in Hz
    channels (PositiveIntegerField): Number of audio channels
    normalize (BooleanField): Whether to apply audio normalization
rw   Tz!Name for this audio configurationrx   ry   aac))r   AAC)mp3MP3)opusOpuszAudio codec to use for encodingr   128kz$Audio bitrate (e.g., '128k', '256k')r{   逻  ))i@  z8 kHz)i>  z16 kHz)i"V  z	22.05 kHz)iD  z44.1 kHz)r   z48 kHz)i w z96 kHzzAudio sample rate in Hz)r$   r   r      ))r+   Mono)r   Stereo)r'   z5.1 SurroundzNumber of audio channelsz+Apply audio normalization (loudnorm filter)r$   r   c                   "    \ rS rSrSrSrS/rSrg)AudioConfiguration.MetaiU  zAudio ConfigurationzAudio Configurationsr4   r:   Nr   r:   rF   rG   rH   r   U  r   rF   rH   c                 :    U R                    SU R                   S3$ )z1String representation of the audio configuration.r   r   )r4   bitraterJ   s    rG   rL   AudioConfiguration.__str__Z  s    ))Bt||nA..rF   r:   N)r<   r=   r>   r?   rd   r   re   r4   r   r   rl   sample_rater,   rk   	normalizerH   rL   rE   r:   rF   rG   r   r     s    " 5D 

 4	E 8G --
 ,K **

 -H ##?I
 
/rF   r   c                      \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " \
\R                  SSSS9r\R                  " \\R                  SSS	S9r\R                  " SSS
S9r\R                  " SSSS9r\R$                  " SSS9r\R$                  " SSS9r\R*                  " SSS9r\R.                  " SSSS9r\R2                  " \SSS9r " S S5      rS rS rS rS r Sr!g) StreamSessioni_  aK  
Model representing an active or historical stream session.

A stream session tracks a specific instance of stream capture
and processing, including start/end times, configuration used,
and processing statistics.

Attributes:
    channel (ForeignKey): Channel this session belongs to
    video_config (ForeignKey): Video configuration used
    audio_config (ForeignKey): Audio configuration used
    started_at (DateTimeField): When the session started
    ended_at (DateTimeField): When the session ended (if applicable)
    segments_processed (PositiveIntegerField): Number of segments processed
    errors_count (PositiveIntegerField): Number of errors encountered
    last_error (TextField): Last error message encountered
    process_id (CharField): System process ID for monitoring
    statistics (JSONField): Additional statistics data
r_   zChannel this session belongs tor-   Tz)Video configuration used for this session)r.   nullr"   r   z)Audio configuration used for this sessionzWhen the stream capture startedr   r"   r   zWhen the stream capture endedr   z)Number of segments successfully processedr   z.Number of errors encountered during processingzLast error message encounteredr!   rw   z System process ID for monitoring)r   r"   r   z"Additional statistics and metadata)r$   r"   r   c                       \ rS rSrSrSrS/r\R                  " SS/S9\R                  " S/S9\R                  " S/S9/r	S	r
g
)StreamSession.Metai  zStream SessionzStream Sessionsz-started_atchannelr^   r6   
started_atr:   Nr;   r:   rF   rG   rH   r     sH    '/!?LLH 56LL/LL
+
rF   rH   c                 h    U R                   R                   SU R                   SU R                   S3$ )z,String representation of the stream session.z - r   r   )r   r4   r^   r   rJ   s    rG   rL   StreamSession.__str__  s/    ,,##$C}Bt6GqIIrF   c                     U R                   (       a6  U R                  =(       d    [        R                  " 5       nXR                   -
  $ g)z&Calculate the duration of the session.N)r   ended_atr   now)rK   end_times     rG   durationStreamSession.duration  s-    ??}}6Hoo--rF   c                 P    U R                   S;   =(       a    U R                  (       + $ )z*Check if the session is currently running.)r]   
processing)r^   r   rJ   s    rG   
is_runningStreamSession.is_running  s    {{66Lt}};LLrF   c                 \    U =R                   S-  sl         Xl        U R                  SS/S9  g)z6Add an error to the session and increment error count.r+   errors_count
last_errorupdate_fieldsN)r   r   save)rK   error_messages     rG   	add_errorStreamSession.add_error  s+    Q'		 >	?rF   )r   N)"r<   r=   r>   r?   rd   r   rq   r   rr   r   ru   SET_NULLvideo_configr   audio_configDateTimeFieldr   r   rl   segments_processedr   ri   r   re   
process_id	JSONFielddict
statisticsrH   rL   r   r   r   rE   r:   rF   rG   r   r   _  sI   * ..3	G $$//=L $$//=L %%3J ##1H  44=
 ..BL
 !!2J !!4J !!6J
 
JM@rF   r   c                      \ rS rSrSr\R                  " \\R                  SSS9r	\R                  " SSS9r\R                  " S	S
S9r\R                  " SS9r\R                  " \" S5      \" S5      /SS9r\R&                  " SSSS9r\R*                  " SSS9r\R.                  " SSSS9r " S S5      rS rS rS rS rSrg) 
HLSSegmenti  a  
Model representing an individual HLS segment file.

This model tracks individual .ts segment files that make up
the HLS stream, including their metadata, file paths, and
processing status.

Attributes:
    session (ForeignKey): Stream session this segment belongs to
    filename (CharField): Name of the segment file
    file_path (CharField): Full path to the segment file
    sequence_number (PositiveIntegerField): Sequence number in playlist
    duration (FloatField): Duration of the segment in seconds
    file_size (PositiveBigIntegerField): Size of the segment file in bytes
    processed_at (DateTimeField): When the segment was processed
    is_available (BooleanField): Whether the file is currently available
segmentsz&Stream session this segment belongs tor-   r&   zName of the segment file)r   r   r    zFull path to the segment filez#Sequence number in the HLS playlist)r   g?g      N@z"Duration of the segment in seconds)r   r   Tz!Size of the segment file in bytesr   zWhen the segment was processed)auto_now_addr   z/Whether the segment file is currently availabler#   c                       \ rS rSrSrSrSS/rSS/r\R                  " SS/S9\R                  " S/S9\R                  " S/S9/r
S	rg
)HLSSegment.Metai  zHLS SegmentzHLS Segmentssessionsequence_numberr6   processed_atis_availabler:   N)r<   r=   r>   r?   r@   rA   rB   unique_togetherr   rC   rD   rE   r:   rF   rG   rH   r     sZ    $,01$&78LL,= >?LL 01LL 01
rF   rH   c                 `    U R                   R                  R                   SU R                   3$ )z)String representation of the HLS segment.z - Segment )r   r   r4   r   rJ   s    rG   rL   HLSSegment.__str__$  s+    ,,&&++,K8L8L7MNNrF   c                 T    [         R                  R                  U R                  5      $ )z2Check if the segment file actually exists on disk.)rO   rP   exists	file_pathrJ   s    rG   file_existsHLSSegment.file_exists(  s    ww~~dnn--rF   c                 v     [         R                  R                  U R                  5      $ ! [         a     gf = f)z#Get the actual file size from disk.N)rO   rP   getsizer   OSErrorrJ   s    rG   get_file_sizeHLSSegment.get_file_size,  s0    	77??4>>22 		s   (+ 
88c                      [         R                  R                  U R                  5      (       a8  [         R                  " U R                  5        SU l        U R                  S/S9  g g! [         a     gf = f)z"Delete the segment file from disk.Fr   r   T)rO   rP   r   r   remover   r   r   rJ   s    rG   delete_fileHLSSegment.delete_file3  sk    	ww~~dnn--		$..)$)!		(8	9	 .   		s   A%A* *
A76A7)r   N)r<   r=   r>   r?   rd   r   rq   r   rr   r   re   filenamer   rl   r   
FloatFieldr   r   r   PositiveBigIntegerField	file_sizer   r   rk   r   rH   rL   r   r   r   rE   r:   rF   rG   r   r     s   & ..:	G ,H
   1I 117O   %c*,=d,CD6H
 ..5I ''2L
 &&CL	
 	
O.
rF   r   )#rd   	django.dbr   django.contrib.auth.modelsr   django.utilsr   django.core.validatorsr   r   apps.core.modelsr   r	   r
   apps.core.validatorsr   r   r   r   r   r   r   r   r   r   r   r   r   rO   jsonr   ru   r   r   r   r:   rF   rG   <module>r     s     + ! G E E    
 |=	 |=~q2)9 q2hO/)9 O/du@$i u@pf!9 frF   