#!/usr/bin/env bash set -euo pipefail usage() { echo "Использование: $0 <папка с главами> [--title текст] [--author текст] [--bitrate 64k] [--force]" } src="${1:-}" out="${2:-}" if [[ -z "$src" || -z "$out" ]]; then usage >&2 exit 2 fi shift 2 || true title="" author="" bitrate="64k" force=0 while [[ $# -gt 0 ]]; do case "$1" in --title) title="${2:-}"; shift 2 ;; --author) author="${2:-}"; shift 2 ;; --bitrate) bitrate="${2:-}"; shift 2 ;; --force) force=1; shift ;; -h|--help) usage; exit 0 ;; *) echo "Неизвестный аргумент: $1" >&2; exit 2 ;; esac done if [[ ! -d "$src" ]]; then echo "Папка не найдена: $src" >&2 exit 2 fi if ! command -v ffmpeg >/dev/null 2>&1 || ! command -v ffprobe >/dev/null 2>&1; then echo "ffmpeg и ffprobe должны быть установлены." >&2 exit 1 fi if [[ -e "$out" && "$force" -eq 0 ]]; then echo "Файл уже существует: $out. Добавьте --force." >&2 exit 1 fi mkdir -p "$(dirname "$out")" out="$(cd "$(dirname "$out")" && pwd)/$(basename "$out")" mapfile -t found < <( find "$src" -maxdepth 1 -type f \ \( -iname '*.mp3' -o -iname '*.m4a' -o -iname '*.flac' \ -o -iname '*.wav' -o -iname '*.ogg' -o -iname '*.aac' \) \ -print | LC_ALL=C sort ) files=() for file in "${found[@]}"; do absolute="$(cd "$(dirname "$file")" && pwd)/$(basename "$file")" if [[ "$absolute" != "$out" ]]; then files+=("$file") fi done if [[ "${#files[@]}" -eq 0 ]]; then echo "Главы не найдены." >&2 exit 1 fi escape() { printf '%s' "$1" | sed -e 's/\\/\\\\/g' -e 's/;/\\;/g' -e 's/#/\\#/g' -e 's/=/\\=/g' } tmpdir="$(mktemp -d)" trap 'rm -rf "$tmpdir"' EXIT meta="$tmpdir/chapters.ffmeta" input_args=() filter="" concat_inputs="" index=0 for file in "${files[@]}"; do absolute="$(cd "$(dirname "$file")" && pwd)/$(basename "$file")" input_args+=(-i "$absolute") filter+="[${index}:a]aresample=44100,aformat=sample_fmts=fltp:channel_layouts=mono[a${index}];" concat_inputs+="[a${index}]" index=$((index + 1)) done filter+="${concat_inputs}concat=n=${#files[@]}:v=0:a=1[out]" { echo ";FFMETADATA1" if [[ -n "$title" ]]; then echo "title=$(escape "$title")" fi if [[ -n "$author" ]]; then echo "artist=$(escape "$author")" fi start_ms=0 for file in "${files[@]}"; do duration="$(ffprobe -v error -show_entries format=duration \ -of default=nw=1:nk=1 "$file")" if ! [[ "$duration" =~ ^[0-9]+([.][0-9]+)?$ ]]; then echo "Не удалось прочитать длительность: $file" >&2 exit 2 fi duration_ms="$(awk -v d="$duration" 'BEGIN { printf "%d", d * 1000 }')" end_ms=$((start_ms + duration_ms)) name="$(basename "$file")" name="${name%.*}" echo "[CHAPTER]" echo "TIMEBASE=1/1000" echo "START=$start_ms" echo "END=$end_ms" echo "title=$(escape "$name")" start_ms=$end_ms done } > "$meta" ffmpeg -hide_banner -loglevel error -nostdin "${input_args[@]}" -i "$meta" \ -filter_complex "$filter" -map "[out]" \ -map_metadata "$index" -map_chapters "$index" \ -c:a aac -b:a "$bitrate" -ac 1 -ar 44100 \ -movflags +faststart -y "$out" echo "Готово: $out" echo "Глав: ${#files[@]}, битрейт: $bitrate"