Anime

get_showname() {
    local filename="$1"

    if [ -z "$filename" ]; then
        echo "Usage: clean_basename 'filename.mkv'" >&2
        return 1
    fi

    # Extract just the filename without path
    filename=$(basename "$filename")

    # Extract season and episode (e.g., S01E01)
    if [[ $filename =~ (S[0-9]{2}E[0-9]{2}) ]]; then
        season_episode="${BASH_REMATCH[1]}"

        # Get the part before the season/episode
        show_part="${filename%%$season_episode*}"

        # Replace dots with spaces and clean up
        show_name=$(echo "$show_part" | sed 's/\.\./\./g' | sed 's/\./ /g' | sed 's/ *$//')

        # Return formatted filename
        echo "${show_name}"
    else
        echo "Error: Could not find season/episode pattern in filename" >&2
        return 1
    fi
}

clean_basename() {
    local filename="$1"

    if [ -z "$filename" ]; then
        echo "Usage: clean_basename 'filename.mkv'" >&2
        return 1
    fi

    # Extract just the filename without path
    filename=$(basename "$filename")

    # Extract season and episode (e.g., S01E01)
    if [[ $filename =~ (S[0-9]{2}E[0-9]{2}) ]]; then
        season_episode="${BASH_REMATCH[1]}"

        # Get the part before the season/episode
        show_part="${filename%%$season_episode*}"

        # Replace dots with spaces and clean up
        show_name=$(echo "$show_part" | sed 's/\.\./\./g' | sed 's/\./ /g' | sed 's/ *$//')

        # Get file extension
        extension="${filename##*.}"

        # Return formatted filename
        echo "${show_name} - ${season_episode}.${extension}"
    else
        echo "Error: Could not find season/episode pattern in filename" >&2
        return 1
    fi
}

format_audio_info() {
    local input="$1"
    local tracks=$(get_audio_tracks "$input")

    # Store tracks in arrays
    local -a codecs languages channel_counts
    while IFS=':' read -r index codec channels lang; do
        codecs+=("$codec")
        channel_counts+=("$channels")
        languages+=("$lang")
    done <<< "$tracks"

    # Check if all codecs and channels are the same
    local all_same=true
    local first_codec="${codecs[0]}"
    local first_channels="${channel_counts[0]}"
    for i in "${!codecs[@]}"; do
        if [[ "${codecs[$i]}" != "$first_codec" ]] || [[ "${channel_counts[$i]}" != "$first_channels" ]]; then
            all_same=false
            break
        fi
    done

    # Format output
    if [[ "$all_same" == true ]] && [[ ${#codecs[@]} -gt 1 ]]; then
        local channel_suffix=$(format_channels "$first_channels")
        echo "Dual Audio ${first_codec^^}${channel_suffix}"
    else
        local output=""
        for i in "${!codecs[@]}"; do
            local channel_suffix=$(format_channels "${channel_counts[$i]}")
            [[ -n "$output" ]] && output+=" "
            output+="${languages[$i]^^} ${codecs[$i]^^}${channel_suffix}"
        done
        echo "$output"
    fi
}

generate_output_filename() {
    local input="$1"
    local resolution="$2"
    local hdr="$3"
    local audio="$4"
    local basename=$(basename "$input" .mkv)

    echo "${basename} [${resolution}] [AV1 10bit ${hdr}] [${audio}].mkv"
}

reenocde_av1() {
    local input="$1"
    local path="$2"
    local output="$3"
    create_output_directory "$OUTPUT_PATH"

    # Find the first English subtitle track with "Forced" in the title
    # Get both the absolute stream index and calculate the relative subtitle index
    forced_sub_info=$(ffprobe -v error -select_streams s -show_entries stream=index:stream_tags=language,title -of csv=p=0 "$input" | \
      awk -F',' 'BEGIN{sub_idx=0} {if($2=="eng" && tolower($3) ~ /forced/) {print $1","sub_idx; exit} sub_idx++}')

    forced_sub_absolute=$(echo "$forced_sub_info" | cut -d',' -f1)
    forced_sub_relative=$(echo "$forced_sub_info" | cut -d',' -f2)

    # Check if any English subtitles exist
    eng_subs_exist=$(ffprobe -v error -select_streams s -show_entries stream_tags=language -of csv=p=0 "$input" | grep -q "eng" && echo "yes" || echo "no")

    # Build base command
    local map_args="-map 0:v:0 -map 0:a"
    local vf_args="scale=in_range=tv:out_range=tv"

    # Add subtitle mapping if English subs exist
    if [ "$eng_subs_exist" = "yes" ]; then
        map_args="$map_args -map 0:s:m:language:eng"

        # If we're burning a forced track, exclude it from passthrough
        if [ -n "$forced_sub_absolute" ]; then
            map_args="$map_args -map -0:$forced_sub_absolute"
        fi
    fi

    # Add forced subtitle burn-in if found
    if [ -n "$forced_sub_relative" ]; then
        vf_args="$vf_args,subtitles='$input':si=$forced_sub_relative"
        echo "Burning in forced subtitle: stream $forced_sub_absolute (subtitle index $forced_sub_relative)"
    else
        echo "No forced subtitle found"
    fi

    # Single ffmpeg command
    ffmpeg -i "$input" \
        $map_args \
        -c:v libsvtav1 \
        -preset 5 \
        -crf 30 \
        -pix_fmt yuv420p10le \
        -svtav1-params "fast-decode=1:tune=0:film-grain=10:film-grain-denoise=0" \
        -vf "$vf_args" \
        -map_metadata 0 \
        -c:a copy \
        $sub_codec_arg \
        -f matroska \
        "$path$output"
}
