Skip to content

Instantly share code, notes, and snippets.

@wata
Created December 10, 2024 15:10
Show Gist options
  • Save wata/71ce65a3dd347b78378b30ddbc691cb2 to your computer and use it in GitHub Desktop.
Save wata/71ce65a3dd347b78378b30ddbc691cb2 to your computer and use it in GitHub Desktop.
Macのフォルダアクション用、動画ファイルをHEVCで再エンコードするスクリプト
wait_until_ready() {
local file="$1"
local timeout=30 # 最大待機時間(秒)
local elapsed=0
echo "Waiting for $file to be ready..."
# ファイルが準備完了するまでループ
while :; do
# kMDItemDurationSeconds を取得
duration=$(mdls -name kMDItemDurationSeconds "$file" 2>/dev/null | awk '{print $3}')
# duration が取得でき、かつ正の値なら準備完了
if [[ -n "$duration" && "$duration" != "(null)" && "$duration" > 0 ]]; then
echo "$file is ready (duration: $duration seconds)."
break
fi
# 待機時間がタイムアウトを超えたらエラー
if (( elapsed >= timeout )); then
echo "Timeout waiting for $file to be ready."
return 1
fi
# 1秒待機して経過時間を増加
sleep 1
((elapsed++))
done
}
for file in "$@"; do
if ! wait_until_ready "$file"; then
mv "$file" "${file%.*}_timeouted.${file##*.}"
continue
fi
filename=$(stat -f "%SB" -t "%Y%m%d" "$file")
extension="${file##*.}"
directory="/Volumes/share1"
duration=$(mdls -name kMDItemDurationSeconds "$file" | awk '{print $3}' | xargs printf "%.0f")
hours=$((duration / 3600))
minutes=$(( (duration % 3600) / 60 ))
seconds=$((duration % 60))
time=""
if ((hours > 0)); then
time+="${hours}h"
fi
if ((minutes > 0)); then
time+="${minutes}m"
fi
if ((seconds > 0)); then
time+="${seconds}s"
fi
codec=$(mdls -name kMDItemCodecs "$file")
if [[ "$codec" == *HEVC* ]]; then
output="${directory}/${filename}_${time}.${extension}"
cp "$file" "$output" && rm "$file"
return
fi
output="${directory}/${filename}_${time}_encoded.${extension}"
command="/opt/homebrew/bin/ffmpeg -i \"$file\" -c:a copy -c:v libx265 -crf 22 -tag:v hvc1 \"$output\""
if eval $command; then
rm "$file"
else
mv "$file" "${file%.*}_failed.${file##*.}"
fi
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment