Processe recursivamente arquivos de vídeo para liberar espaço

Processe recursivamente arquivos de vídeo para liberar espaço

Maximizei o espaço de armazenamento que tenho e gostaria de criar algum espaço.

Pensei em converter todos os arquivos para mkv e reduzir os arquivos de alta resolução para uma resolução mais baixa.

Então, para converter mp4 para mkv existe

ffmpeg -i input.mp4 -vcodec copy -acodec copy output.mkv

E para diminuir a escala há

ffmpeg -i input.mp4 -vf scale=$w:$h <encoding-parameters> output.mp4

mas preciso converter todos os arquivos, não um único mp4, preciso remover o arquivo de entrada após terminar de processá-lo e tenho que fazer isso apenas para arquivos acima de uma determinada resolução. Também gostaria de manter a proporção e não sei se isso está acontecendo.

Existe uma ferramenta chamadadieta de vídeoisso faz parte disso.

Isto é o que eu gostaria de fazer

Recursively find every file under the current directory
If the file resolution has a height equal or greater to a given height.
  Convert the file to mkv if it's in another format avi, mp4, flv, etc
  Downscale to a lower resolution height, keeping the aspect ratio.

Talvez eu também devessediminuir a taxa de quadrospara 24fps?

Se houver uma maneira melhor, eu gostaria de ouvi-la.

Responder1

Aqui está um script para você começar. Você provavelmente desejará modificar isso para atender às suas necessidades, adicionar opções ao ffmpeg se quiser alterar a taxa de quadros, etc.

Observe que há uma condicional verificando se o arquivo já é um .mkv, mas na verdade não estou fazendo algo diferente com eles, então a condicional é meio inútil. Só está aí porque sua pergunta fez parecer que você queria fazer algo diferente com eles, embora eu não saiba por quê. O FFMPEG pode dimensionar e converter ao mesmo tempo.

Mas se você quiser fazer algo diferente, altere a linha ffmpeg para quando a condicional for verdadeira para algo diferente.

#!/bin/bash

# set the resolution above which you want to downscale
maxwidth=1920
maxheight=1080

# set the resolution to downscale to; the width will be
# calculated to preserve aspect ratio
targetwidth=1280

# a counter for errors
errors=0

# recursively find video files; add their names to
# an array to process
mapfile -t filenames < <(find $(pwd) -type f -iregex '.*avi$\|.*mp4$\|.*m4v$\|.*flv\|.*mkv\|.*ogv\|.*webm$\|.*mov')

# loop through the array
for filename in "${filenames[@]}" ; do
    # get the resolution with ffprobe
    res="$(ffprobe -hide_banner -v error -select_streams v:0 -show_entries stream=width,height -print_format csv "$filename")"
    # strip "stream" off "res"
    res="${res#stream,}"
    # parse into width and height
    width="${res%,*}"
    height="${res#*,}"
    # compare to maxwidth/height to see if it should be
    # processed
    if [[ "$width" -ge "$maxwidth" ]] || [[ "$height" -ge "$maxheight" ]] ; then
        # determine the output name
        outputname="${filename%.*}-downscaled.mkv"
        # check if output already exists; if so, skip it
        if [[ -e "$outputname" ]] ; then
            continue
        fi
        # calculate targetheight, divide by 2 multiply by 2
        # to ensure it's even
        targetheight="$(( ( ( (targetwidth * height) / width) / 2) * 2 ))"
        # get file extension
        ext="${filename##*.}"
        # do something different with mkvs?
        # not sure why you would though
        if [[ "$ext" =~ '[Mm]{Kk][Vv]' ]] ; then
            ffmpeg -i "$filename" -vf scale="$targetwidth:$targetheight" "$outputname"
            exitcode="$?"
        else
            ffmpeg -i "$filename" -vf scale="$targetwidth:$targetheight" "$outputname"
            exitcode="$?"
        fi
        # if conversion was a success, delete original file
        if [[ "$exitcode" == 0 ]] && [[ -e "$outputname" ]] ; then
            rm "$filename"
        else
            echo
            echo "Error processing $filename" >&2
            echo "Not deleted!"
            let errors++
            echo
        fi
    fi
done

# report number of errors if there were any
if [[ "$errors" == 0 ]] ; then
    exit 0
fi
echo "There were $errors errors!" >&2
exit 1

Isso pode ser um exagero e pode haver maneiras de simplificá-lo, mas é o que eu faria.

informação relacionada