#!/bin/bash

mkdir -p out

# Réglages Qualité (Bitrate)
# Source à 15Mbps HEVC -> On vise ~8Mbps H.264 pour un bon compromis qualité/poids
BITRATE="15000k"
MAXRATE="15500k"
BUFSIZE="28000k"

while true; do
  echo "Démarrage du transcodage (Source 50fps Progressive)..."
  
  ffmpeg -hide_banner -loglevel info -stats -stats_period 1 \
  -nostdin -re \
  -reconnect 1 -reconnect_streamed 1 -reconnect_at_eof 1 -reconnect_on_network_error 1 -reconnect_delay_max 5 \
  -rw_timeout 15000000 \
  -thread_queue_size 4096 \
  -user_agent "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36" \
  -i "http://direct-local.com:8080/IPTVStreamNow4028/vHimB5DdOiPEILfTpr4h5QJY/146" \
  -map 0:v:0 -map 0:a:0? \
  -c:v libx264 -preset veryfast -profile:v high -level 4.2 \
  -b:v $BITRATE -maxrate $MAXRATE -bufsize $BUFSIZE \
  -g 100 -keyint_min 100 -sc_threshold 0 \
  -c:a copy \
  -muxdelay 0 -muxpreload 0 \
  -f hls \
  -hls_time 2 \
  -hls_list_size 10 \
  -hls_flags delete_segments+append_list+independent_segments+temp_file+program_date_time+omit_endlist \
  -hls_segment_filename "out/seg_%08d.ts" \
  out/index.m3u8 || true

  echo "Flux interrompu. Nouvelle tentative dans 2s..."
  sleep 2
done
